スルー関係を使用して、ファクトリ ボーイの一連の 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)
単純化された factory.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)
ただし、これを行うと、どちらの側にも多対多の関係が設定されず、recipingredient モデル自体の作成に失敗するようにも見えます。これを行う方法を知っている人はいますか?
編集:
私も試しました:
class RecipeWith3Ingredients(RecipeFactory):
ingredient1 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
ingredient2 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
ingredient3 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
しかし、既存のレシピと材料のセットを使用してこれらのオブジェクトを作成する方法について頭を悩ませることはできません。