from django.db import modelsclass Person(models.Model):SEX_CHOICES = (('M', 'Male'),('F', 'Female'),)name = models.CharField(max_length=255)sex = models.CharField(max_length=255, choices=SEX_CHOICES)city = models.CharField(max_length=255)height = models.DecimalField(max_digits=10, decimal_places=2)def __unicode__(self):return self.name
import djangodjango.setup()from testapp.models import Person# Get a list consisting of the tallest female in each city.tallest_females = Person.objects.filter(sex='F').order_by('city', '-height').distinct('city').values_list('pk', flat=True)print tallest_females.query# This outputs:## SELECT DISTINCT ON ("testapp_person"."city") "testapp_person"."id"# FROM "testapp_person"# WHERE "testapp_person"."sex" = F# ORDER BY "testapp_person"."city" ASC, "testapp_person"."height" DESC# Get a list consiting of females who are the tallest (among all people) in# their respective cities.# How do I get this list using the ORM? Note that I am having resort to# filtering results in Python.tallest_people = Person.objects.order_by('city', '-height').distinct('city').values_list('pk', flat=True)females_who_are_tallest_in_their_city = [ p for p in tallest_people if (p in tallest_females) ]# Ideally, I'd like to write:# Person.objects.order_by('city', '-height').distinct('city').filter(sex='F').values_list('pk', flat=True)
Person.objects.filter(sex='F', pk__in=tallest_people)