Search code examples
pythondjangom2mdatabase-optimization

Django many2many is a subset of another set


Given a model with an m2m field, let's say Article has multiple Authors. What is the most efficient way to get all the articles in which the set of their authors is a subset of another set?

class Article(models.Model):
    authors = models.ManyToManyField('Author')

Get all articles that were written by one or many of the authors in this list but doesn't have any author that is not part of this list.

authors_list = ['Tom', 'John', 'Sara', 'Kati']
  • Articles written by 'Tom' would match.
  • Articles written by 'Tom' and 'Sara' would match.
  • But, Articles written by 'Tom' and 'Alter' would NOT match.

Solution

  • Without knowing more about your author model, this is just a guess, but this general approach should work:

    authors = Author.objects.filter(first_name__in=authors_list)
    others = Author.objects.exclude(first_name__in=authors_list)
    queryset = Article.objects.filter(authors__in=authors)
    queryset = queryset.exclude(authors__in=others)