I have had this annoyance with ModelMommy for a while but I can't figure out how to do this properly.
Let`s assume a simple relation:
class Organization(models.Model):
label = models.CharField(unique=True)
class Asset(models.Model):
organization = models.ForeignKey(Organization)
label = models.CharField(unique=True)
And recipes:
from model_mommy.recipe import Recipe, foreign_key
organization_recipe = Recipe(Organization, label='My Organization')
asset1_recipe = Recipe(Asset,
organization=foreign_key(organization_recipe),
label='asset 1')
asset2_recipe = Recipe(Asset,
organization=foreign_key(organization_recipe),
label='asset 2')
Now when I make these asset recipes I get an error:
>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make()
IntegrityError: duplicate key value violates unique constraint "organizations_organization_label_key"
DETAIL: Key (label)=(My Organization) already exists.
This can be solved by providing asset1's organization as a parameter into asset2's make method:
>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make(organization=asset1.organization)
But there has to be a simpler, more clean way of doing this.
Aucun commentaire:
Enregistrer un commentaire