我在使用直通关系与 factory boy 中的一组 django 模型建立多对多关系时遇到问题。我有一堆食谱和配料。通过设置数量的模型,食谱和成分之间存在多对多关系。我为每种型号都有工厂,但无法将它们连接起来。
简化模型.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)
简化工厂.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)
这样做虽然不会在任何一方设置多对多关系,而且似乎也无法创建配方配料模型本身。有谁知道这样做的方法?
编辑:
我也试过:
class RecipeWith3Ingredients(RecipeFactory):
ingredient1 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
ingredient2 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
ingredient3 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
但是我无法理解如何使用预先存在的配方和一组成分来创建这些对象。