简体   繁体   English

通过另一个相关模型对查询集进行分组

[英]Grouping a queryset by another related model

I have two models: 我有两个模型:

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)

And I have a queryset: 我有一个查询集:

Stop.objects.filter(approved_ts__isnull=False)

However, when I send the results of this query to the template, I want it grouped by TransitLine . 但是,当我将此查询的结果发送到模板时,我希望将其按TransitLine分组。 How would I approach this? 我将如何处理?

For clarification, in the end, I want the template to look something like this: 为了澄清起见,最后,我希望模板看起来像这样:

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

In the template, you can use regroup ... 在模板中,您可以使用regroup ...

You must order them by TransitLine, while you filter the queryset using 您必须使用TransitLine对其进行排序,同时使用过滤查询集

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

You can check the documentation... 您可以查看文档...

If I understand correctly, you should really just give the template a queryset of TranslitLine s. 如果我理解正确,那么您实际上应该只为模板提供一个TranslitLine的查询集。 Rather than creating a queryset of Stop s, add an approved_stops() method to your TransitLine class like this: 与其创建一个Stop的查询集,不如向您的TransitLine类添加一个approved_stops()TransitLine approved_stops()方法,如下所示:

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)

Then add 'transit_line_list': TransitLine.objects.all() to the template's context and change {% for s in tl.stops.all %} in the template to {% for s in tl.approved_stops.all %} . 然后在模板的上下文中添加'transit_line_list': TransitLine.objects.all()并将模板中的{% for s in tl.stops.all %}中的{% for s in tl.stops.all %}更改为{% for s in tl.stops.all %}中的{% for s in tl.approved_stops.all %}

Do the following: 请执行下列操作:

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

This query selects only the lines that have approved stops. 该查询仅选择已批准停止的行。

JFYI: to find lines that have any stops, do 肯尼迪(JFYI):要查找有停靠点的行,请执行

TransitLine.objects.exclude(stops__id=None).order_by('name')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM