2010-11-09 79 views
0

分組一個查詢集我有兩個型號:由其他相關模型

class Stop(models.Model): 
    line = models.ForeignKey(TransitLine, related_name='stops') 
    name = models.CharField(max_length=32) 
    approved_ts = models.DateTimeField(null=True, blank=True) 

class TransitLine(models.Model): 
    name = models.CharField(max_length=32) 
    desc = models.CharField(max_length=64) 

而且我有一個查詢集:

Stop.objects.filter(approved_ts__isnull=False) 

然而,當我把這個查詢的結果與模板,我想要它按TransitLine分組。我會如何處理這個問題?

爲了清楚,到最後,我希望模板是這個樣子:

<ul> 
{% for tl in transit_line_list %} 
<li> 
    {{ tl.name }}: 
    {% for s in tl.stops.all %} 
    {{ s.name }} 
    {% endfor %} 
    </li> 
{% endfor %} 
</ul> 

回答

1

在模板中,你可以使用regroup ...

您必須通過TransitLine命令他們,當你使用過濾

Stop.objects.filter(approved_ts__isnull=False).order_by('line') 

您可以查看文檔的查詢集...

+0

今晚我回家後我會試試。謝謝!有意義的是它是模板邏輯。 – 2010-11-09 16:06:51

+0

如果您有任何疑問或問題,我可以用一個簡單的例子來解釋用法。它簡單而有用。 – FallenAngel 2010-11-10 07:46:01

+0

謝謝@FallenAngel。像魅力一樣工作。 – 2010-11-12 12:26:03

0

如果我理解正確的,你應該只給模板的TranslitLine個查詢集。而不是創造的Stop個查詢集,添加一個approved_stops()方法您TransitLine類是這樣的:

class TransitLine(models.Model): 
    name = models.CharField(max_length=32) 
    desc = models.CharField(max_length=64) 

    def approved_stops(self): 
     return self.stops.filter(approved_ts__isnull=False) 

模板然後加入'transit_line_list': TransitLine.objects.all()到模板的情況下,改變{% for s in tl.stops.all %}{% for s in tl.approved_stops.all %}

+0

如何我把它昨晚。問題是,我會得到沒有經過批准停靠的TransitLines。這不是世界末日,因爲我可以使用條件來防止顯示TransitLine,但認爲可能有更清晰的方式。 – 2010-11-09 12:34:19

0

執行以下操作:

TransitLine.objects.filter(stops__in=Stops.objects.filter(approved_ts=True)).distinct().order_by('name') 

此查詢僅選擇li已批准停止的奈斯。

JFYI:發現有任何停止線,做

TransitLine.objects.exclude(stops__id=None).order_by('name') 
相關問題