Django Filter row by ManyToManyField so that all m2m are a sublist of a list

I have a list [1,2,3,4] and a django model with a manytomany field id

If id can contain [1,2,3] or [1,5]

How can I return the objects that contain a substring of my list [1,2,3,4] and not anything outside that list [1,5].

I've seen this Django filter queryset __in for *every* item in list. But I only want to return a substring

authors = ['Neil Gaiman', 'Terry Pratchett', 'Lisa Lutz']

query = Q()
for author in authors:
    query |= Q(authors__name__icontains=author)

books = Book.objects.filter(query).distinct()

This should do what I understood from your question.

Back to Top