2013-04-24 71 views
0

我有两个模型。将计数添加到查询集

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()

回答

3

试试这个:

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

>>> print q[0].element_count 
223 

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

+0

感谢。它看起来非常好。 – Azd325 2013-04-24 10:47:28

+0

你知道我如何将它添加为虚拟字段吗? – Azd325 2013-04-24 10:52:21

+0

你是什么意思的虚拟领域? 'element_count'将在执行的SQL查询中成为别名。 – 2013-04-24 11:06:48