Django过滤和注释

时间:2014-03-13 10:28:17

标签: django django-queryset

我有一个名为User的表,其定义如下:

IAM_CHOICES = (
    ('HomeOwner', 'HomeOwner'),
    ('Architect', 'Architect'),
    ('Interior Designer', 'Interior Designer'),
)

class User(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(_('First Name'), max_length=30, blank=True, null=True)
    middle_name = models.CharField(_('Middle Name'), max_length=30, blank=True, null=True)
    last_name = models.CharField(_('Last Name'), max_length=30, blank=True, null=True)
    about_yourself = models.TextField(null=True, blank=True)
    image = models.ImageField(upload_to=get_upload_path, null=True, blank=True)
    email = models.EmailField(_('Email Address'), unique=True,
        help_text=_('Please use your personal Email Address, not your Company or College'))
    address = models.TextField(null=True, blank=True)
    city = models.ForeignKey('common.City', null=True, blank=True)
    state = models.ForeignKey('common.State', null=True, blank=True)
    Iam = models.CharField(max_length=50, choices = IAM_CHOICES, null=True, blank=True)

和城市表定义如下:

class City(models.Model):
    name = models.CharField(max_length=100)

我如何找到大多数用户所在的城市并且是某些Iam选择的? 也就是说例如找到我最大的建筑师(Iam选择型建筑师)来自哪里的城市!

1 个答案:

答案 0 :(得分:1)

您可以订购具有最大数量的建筑师的城市 -

City.objects.filter(user__Iam='Architect').annotate(num_user=Count('user')).orde‌​r_by('-num_user')

首先过滤具有建筑师的城市,然后对建筑师进行计数,然后按降序排列。