Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ManytoMany filter exact list

Suppose I have a list of id's: c = ['1', '2' , '3']

class Topic(Model):

 categories=ManyToManyField(Category)

How can I filter topics that have exact and only categories with id's from c?

like image 889
Andrew Fount Avatar asked Dec 24 '22 23:12

Andrew Fount


1 Answers

You need to call .filter(categories=category_id) for each element in the c list.

c = [1, 2, 3]
topics = reduce(lambda qs, pk: qs.filter(categories=pk), c, Topic.objects.all())

And then if you want to exclude topics with additional categories (e.g. a topic with [1,2,3,4]), then you need to .annotate and .filter on the total count.

c = [1, 2, 3]
initial_qs = Topic.objects.annotate(cnt=models.Count('categories')).filter(cnt=len(c))
topics = reduce(lambda qs, pk: qs.filter(categories=pk), c, initial_qs)
like image 135
Todor Avatar answered Feb 08 '23 23:02

Todor