我有一些类似的模型;
class Ingredient(models.Model):
name = models.CharField(max_length=128)
class Recipe(models.Model):
name = models.CharField(max_length=128)
ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient')
class RecipeIngredient(models.Model):
recipe = models.ForeignKey(Recipe)
ingredient = models.ForeignKey(Ingredient)
如何找到包含所有成分的食谱?
这是一个例子;
>>> i1 = Ingredient(name="egg")
>>> i1.save()
>>> i2 = Ingredient(name="flour")
>>> i2.save()
>>> i3 = Ingredient(name="water")
>>> i3.save()
>>> i4 = Ingredient(name="milk")
>>> i4.save()
>>> i5 = Ingredient(name="sugar")
>>> i5.save()
>>> i6 = Ingredient(name="carrot")
>>> i6.save()
>>> i7 = Ingredient(name="wheat")
>>> i7.save()
>>> r1 = Recipe(name="omelet")
>>> r1.save()
>>> r1.ingredients.add(i1, i2, i3)
>>> r2 = Recipe(name="icecream")
>>> r2.save()
>>> r2.ingredients.add(i3, i4, i5)
>>> test = Recipe.objects.filter(ingredients__in=[i1.id, i2.id, i3.id, i4.id])
>>> test
[<Recipe: omelet>, <Recipe: omelet>, <Recipe: omelet>, <Recipe: icecream>, <Recipe: icecream>]
我只想找到煎蛋卷。因为只有煎蛋卷含有鸡蛋(i1),面粉(i2),水(i3)
由于
答案 0 :(得分:0)
可能把它连在一起吗?
Recipe.objects.filter(ingredients=i1.id).filter(ingredients=i2.id).filter(ingredients=i3.id).filter(ingredients=i4.id)