私は工場関係の男の子のdjangoモデルとの多対多の関係を設定する際に問題を抱えています。私はレシピや食材をたくさん持っています。数量を設定するモデルを通じて、レシピと成分の多対多の関係があります。私は各モデルの工場を持っていますが、それらをリンクさせることはできません。テーブルを介して工場の男の子で動的多対多を設定するにはどうすればよいですか?
簡素化models.py:
class Ingredient(models.Model):
name = models.CharField(max_length=40)
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)
quantity = models.IntegerField(default=1)
簡素化factories.py
class RecipeFactory(factory.django.DjangoModelFactory):
class Meta:
model = Recipe
class IngredientFactory(factory.django.DjangoModelFactory):
class Meta:
model = Ingredient
class RecipeIngredientFactory(factory.django.DjangoModelFactory):
class Meta:
model = RecipeIngredient
recipe = factory.SubFactory(RecipeFactory)
ingredient = factory.SubFactory(IngredientFactory)
quantity = 1
私はfactory.RelatedFactoryをいじってみましたが、本当にどこにも持っていません。いずれかの側に多くの関係に多くを設定していないこのかかわらを行う
recipe = RecipeFactory(name="recipe1")
ingredient = IngredientFactory(name="ingredient1")
ri = RecipeIngredientFactory(recipe=recipe, ingredient=ingredient)
、ともrecipeingredientモデル自体の作成に失敗するようだ:理想的には私は次の操作を行うことができるようにしたいです。誰かがこれを行う方法を知っていますか?
編集:
class RecipeWith3Ingredients(RecipeFactory):
ingredient1 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
ingredient2 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
ingredient3 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
をしかし、私は食材の既存のレシピとセットでこれらのオブジェクトを作成したいどのようにまわりで私の頭を取得カント:
私も試してみました。
ありがとうございました!それは私を少し助けてくれました - 私は実際には私の頭痛を引き起こしていた私の結合モデルでセーブメソッドを持っていたと思う、私はあなたが行っている驚くべき努力のために主にこれを受け入れています - ありがとう! - 賞金はあなたのものです。 – bharling
私は工場の男の子のためのドキュメントは少し誤解していると思うが、スルーテーブルと多くの関係をインスタンス化するための具体的な指示は、あなたが上記のようにそれを行うことができることを実際に示していない。 – bharling
心配しないで、それはいくつかの使用だったうれしい:) – tdsymonds