Given this piece of code (Python & TortoiseORM):
class Recipe(Model):
description = fields.CharField(max_length=1024)
ingredients = fields.ManyToManyField(model_name="models.Ingredient", on_delete=fields.SET_NULL)
class Ingredient(Model):
name = fields.CharField(max_length=128)
How to query all recipes that contain BOTH Ingredient.name="tomato" and Ingredient.name="onion" ? I believe that in Django-ORM it was possible to make some intersection of QuerySets using & operator or intersect method.
Update #1
This query worked but it's a bit messy in my opinion and it's gonna be problematic when I will want to f.e. query all recipes that contain more than 2 ingredients.
subquery = Subquery(Recipe.filter(ingredients__name="onion").values("id"))
await Recipe.filter(pk__in=subquery , ingredients__name="tomato")
Update #2
SELECT "recipe"."description",
"recipe"."id"
FROM "recipe"
LEFT OUTER JOIN "recipe_ingredient"
ON "recipe"."id" = "recipe_ingredient"."recipe_id"
LEFT OUTER JOIN "ingredient"
ON "recipe_ingredient"."ingredient_id" = "ingredient"."id"
WHERE "ingredient"."name" = 'tomato'
AND "ingredient"."name" = 'onion'