I'm having problems setting up a many to many relationship with a set of django models in factory boy, using a through relationship. I have a bunch of recipes and ingredients. There is a many-to-many relation between Recipes and Ingredients through a model that sets a quantity. I have factories for each model but cannot get them to link up.
simplified 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)
simplified 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
I've tried messing with factory.RelatedFactory but haven't really got anywhere. Ideally I just want to be able to do the following:
recipe = RecipeFactory(name="recipe1")
ingredient = IngredientFactory(name="ingredient1")
ri = RecipeIngredientFactory(recipe=recipe, ingredient=ingredient)
Doing this though does not set the many to many relation on either side, and also seems to fail to create the recipeingredient model itself. Does anyone know of a way to do this?
Edit:
I've also tried:
class RecipeWith3Ingredients(RecipeFactory):
ingredient1 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
ingredient2 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
ingredient3 = factory.RelatedFactory(RecipeIngredientFactory, 'recipe')
But cant get my head around how I'd create these objects with a pre-existing recipe and set of ingredients.