저는 공장 관계자를 통해 장고 모델 세트와 다 대다 관계를 설정하는 데 문제가 있습니다. 나는 많은 요리법과 재료를 가지고있다. 수량을 설정하는 모델을 통해 Recipes와 Ingredients 간에는 다 대다 관계가 있습니다. 각 모델에 대한 공장을 가지고 있지만 연결할 수 없습니다.테이블을 통해 공장 소년에게 많은 동적 대다수를 설정하는 방법은 무엇입니까?
단순화 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
나는 factory-boy에 대한 문서가 다소 오도 된 것이라고 생각하지만, through 테이블과 많은 관계를 많이 인스턴스화하는 구체적인 지침은 실제로 위와 같이 할 수 있음을 나타내지는 않지만 실제로 할 수 있습니다. – bharling
걱정하지 않아서 사용하기에 좋았습니다 :) – tdsymonds