2
ModelMommyでこの邪魔されましたが、これを正しく行う方法がわかりません。モデルマミー:1つのレシピに対する外部キーの関係を持つ複数のレシピ
class Organization(models.Model):
label = models.CharField(unique=True)
class Asset(models.Model):
organization = models.ForeignKey(Organization)
label = models.CharField(unique=True)
とレシピ::私はこれらの資産のレシピを作るとき
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')
は今、私はエラーを取得する:
>> 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.
この缶
Let`sは単純な関係を想定しますasset2のmakeメソッドにパラメータとしてasset1の組織を提供することで解決してください:
>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make(organization=asset1.organization)
しかし、これを行うにはもっと簡単できれいな方法が必要です。
def organization_get_or_create(**kwargs):
"""
Returns a closure with details of the organization to be fetched from db or
created. Must be a closure to ensure it's executed within a test case
Parameters
----------
kwargs
the details of the desired organization
Returns
-------
Closure
which returns the desired organization
"""
def get_org():
org, new = models.Organization.objects.get_or_create(**kwargs)
return org
return get_org
my_org = organization_get_or_create(label='My Organization')
asset1_recipe = Recipe(Asset,
organization=my_org,
label='asset 1')
asset2_recipe = Recipe(Asset,
organization=my_org,
label='asset 2')
そして、私が好きなように多くの資産を作成することができます。
EDIT
は、リンクに基づいてHelgiの答えに私は閉鎖を指すようにすべての私のレシピの外部キーを変更しました:
>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make()