将计数添加到queryset

时间:2013-04-24 09:43:33

标签: django django-models

我有两个模特。

class Category(models.Model):
    name = models.CharField()

   @property
   def element_count()
      return Element.objects.filter(name=self.name).count()


class Element(models.Model):
   name = models.CharField()
   categories = models.ManyToManyField(Category)

我希望将每个元素的数量与此类别相关联。 这个函数适用于模板和视图,但有没有办法直接进入查询集?

如果这样做Category.objects.all()

1 个答案:

答案 0 :(得分:3)

试试这个:

>>> from django.db.models import Count
>>> q = Category.objects.all().annotate(element_count = Count('element'))

>>> print q[0].element_count
223

Doc:https://docs.djangoproject.com/en/dev/topics/db/aggregation/