varad
varad

Reputation: 8029

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 ?

Upvotes: 1

Views: 192

Answers (1)

dylrei
dylrei

Reputation: 1738

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)

Upvotes: 1

Related Questions