Search code examples
pythondjangomany-to-many

django many to many field annotate and count


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)

Here what I want is I want to list all the question which dont have any answer.

I did:

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

Is it right way of doing ?


Solution

  • You're close. Here's what you probably want:

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