django许多对很多字段进行注释和计数

时间:2015-03-23 20:27:41

标签: python django many-to-many

I have a model :
class Question(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=120)
    description = models.TextField()
    answers = models.ManyToManyField('Answer',related_name='answer_name', blank=True)

这里我想要的是我想列出所有没有答案的问题。

我做了:

un_list = Question.objects.annotate(a_count="Answers").filter(a_count=0)

这是正确的做法吗?

1 个答案:

答案 0 :(得分:1)

你很亲密。这是你可能想要的:

from django.db.models import Count
un_list = Question.objects.annotate(a_count=Count("answer")).filter(a_count=0)