Given I have a Product
model and a one-to-many ProductTag
model.
class Product(models.Model):
[...]
class ProductTag(models.Model):
product = models.ForeignKey(Product)
tag_value = models.CharField()
[...]
If I have 3 products with some tags:
- ProductA [TagA]
- ProductB [TagB]
- ProductC [TagB/TagC]
I want to dynamically query "products" with some tags.
- This query returns just "ProductA" (as expected).
Product.objects.filter(Q(producttag__tag_value="TagA"))
- This query returns all 3 products (as expected).
Product.objects.filter(
Q(producttag__tag_value="TagA") | Q(producttag__tag_value="TagB")
)
- I would expect the following query to return just "ProductC"
Product.objects.filter(
Q(producttag__tag_value="TagB") & Q(producttag__tag_value="TagC")
)
But I get an empty queryset. Why does query #3 not work?
Using __in
query also returns wrong results (as expected)
Product.objects.filter(producttag__tag_value__in=["TagB", "TagC"])
The above query returns both ProductB / ProductC.
UPDATE
The reason why I am doing lookups with Q objects is that the query is based on user input from an API endpoint. e.g
- "tag=TagA"
- "tag=TagA AND tag=TagB"
- "tag=TagA AND NOT tag=TagC"
So I need to run a dynamic Django query based on the user input and not able to hardcode some query.