简体   繁体   中英

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 . 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 ...

You must order them by TransitLine, while you filter the queryset using

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. Rather than creating a queryset of Stop s, add an approved_stops() method to your TransitLine class like this:

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 %} .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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