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:
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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With