[Answer]-Django: quering model with many-to-many fields

1👍

You use the __in operator

Book.objects.filter(subjects__in=[2,4])

It can also be used with a queryset

Book.objects.filter(
     subjects__in=Subject.objects.filter(name__contains="interesting"))

If you instead want Book with both subjects and not just any of them we can use the Q object

Book.objects.filter( Q(subject__in=[2]) & Q(subject__in=[4]) )

Note that the any of operators doest logically fit in to a get_or_create because there isnt enough information to create so you might have to split it up.

👤krs

Leave a comment