2

そのようなモデルがいくつかあります。

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)が入っているのはオムレツだけなので

ありがとう

4

1 に答える 1

0

多分それを一緒に連鎖させますか?

Recipe.objects.filter(ingredients=i1.id).filter(ingredients=i2.id).filter(ingredients=i3.id).filter(ingredients=i4.id)
于 2013-02-28T19:46:10.427 に答える