Django,捆绑计数查询?

时间:2016-10-23 01:30:36

标签: django optimization django-queryset

让我说我有关系

class Person(models.Model):
      is_asian  = models.BooleanField()
      is_male   = models.BooleanField()
      is_gay    = models.BooleanField()
      last_name = models.ForeignKey('FamilyName')
      is_happy  = models.BooleanField()

class FamilyName(models.Model):
      title = models.CharField(max_length=200, primary_key=True)

目前,当我想获得一些关于我的人口的统计数据时,

have_x_many_males   = Person.objects.filter(is_male=True).count()
have_x_many_gays    = Person.objects.filter(is_gay=True).count()
have_x_many_roberts = Person.objects.filter(last_name_id='robert').count()
...

然而,如果我增长的统计数量

,这是非常低效的

有没有办法完全捆绑查询并立即执行它们并返回列表或其他内容?

>>> main_query = [query_1, query_2, query_3]
>>> main_query.execute()
{'have_x_many_males':5, ...}

2 个答案:

答案 0 :(得分:2)

请参阅Conditional aggregation

from django.db import models

aggregates = {
    'have_x_many_males': models.Sum(models.Case(models.When(is_male=True, then=1), output_field = models.IntegerField())),
    'have_x_many_roberts': models.Sum(models.Case(models.When(last_name_id='robert', then=1), output_field = models.IntegerField())),
}

queryset = Person.objects.all().annotate(**aggregates)

答案 1 :(得分:-1)

class Person(models.Model):
    is_asian  = models.BooleanField()
    is_male   = models.BooleanField()
    is_gay    = models.BooleanField()
    last_name = models.ForeignKey('FamilyName')
    is_happy  = models.BooleanField()

    def get_count(self):
        return{
            'have_x_many_males': Person.objects.filter(is_male=True).count()
            'have_x_many_gays': Person.objects.filter(is_gay=True).count()
            'have_x_many_robertss': Person.objects.filter(last_name_id='robert').count()
        }

然后执行p = Person.objects.all().get_count()