Search code examples
pythondjangodjango-modelsdjango-querysetdjango-orm

How to apply filter on django ManyToManyField so that multiple value of the field follow the condition?


class Publication(models.Model):
    title = models.CharField(max_length=30)


class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

p1 = Publication.objects.create(title='The Python Journal')
p2 = Publication.objects.create(title='Science News')
p3 = Publication.objects.create(title='Science Weekly')

I want to filter articles, published in both p1 and p3. They might or might not publish in other publications but they must have to publish in p1 and p3.

I have tried:

Article.objects.filter(Q(publications=p1) & Q(publications=p3))

but it returns empty queryset which is not true


Solution

  • If you chain mutliple calls to filter() they should behave like being connected with an AND:

    articles = Article.objects.filter(publications=p1).filter(publications=p3).distinct()