4

I want to filter using annotate.

Here is my code:

class Blog(models.Model):
    name = models.CharField(max_length=100)

class Reader(models.Model):
    name = models.CharField(max_length=50)
    blog= models.ForeignKey(Blog)
    type = models.ForeignKey(ReaderType)

class ReaderType(models.Model):
    name = models.CharField(max_length=50)

I want to get all the blog's that has at least 2 Reader of type "male". I have this code to get the blogs that have at least 2 Readers:

Blog.objects.annotate(reader_count=Count(reader)).filter(reader_count__gte=2)

How do I add the part that filter only the blogs that have at least 2 readers that their type="male"

1 Answer 1

4

You can just filter on the reader type directly in your query:

posts_with_multiple_readers = (
    Blog.objects.filter(reader__type__name='male')
    .annotate(reader_count=Count('reader'))
    .filter(reader_count__gte=2)
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.