简体   繁体   中英

Django filter on related field using annotate

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM