Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter where ManyToMany field contains ALL of list [duplicate]

Tags:

python

django

I have a CartItem model with a ManyToMany field to a AttributeChoice model. So for example a CartItem can have AttributeChoice "Small" and "Red".

I want to then find my CartItem that both have attributes "Small" and "Red". If I do the following:

CartItem.objects.get(cart=cart, product=product, attribute__in=attribute_list)

Where attribute_list is a list of AttributeChoice objects for "Small" and "Red". Then I will also get objects that only have "Small" or "Red", but not both.

So this query would both match:

  • CartItem A, Small, Red
  • CartItem B, Small
  • CartItem C, Red

While what I want is a query that would only match CartItem A.

Now... I could create a lot of AND-statements, but I need a solution that is flexible and can contain 1 or 100 of attributes to filter for. So to pass it a list of objects would be great.

Ideas?

like image 750
Marcus Lind Avatar asked Dec 19 '22 23:12

Marcus Lind


1 Answers

The solution to this problem was posted in this thread.

This is how I wrote my query:

CartItem.objects.filter(cart=cart, product=product, attribute__in=attribute_list).annotate(num_attr=Count('attribute')).filter(num_attr=len(attribute_list))
like image 150
Marcus Lind Avatar answered Jan 13 '23 15:01

Marcus Lind