2
我有ModelMommy有一段時間的煩惱,但我無法弄清楚如何正確地做到這一點。模型媽咪:與單一配方的外鍵關係的多個食譜
突然想到假設一個簡單的關係:
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.
這可以通過提供asset1的組織作爲asset2的make方法的參數來解決:
>> 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')
而且我喜歡可以創造儘可能多的資產:
>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make()