[英]Model Mommy: Multiple recipes with foreign key relation to a single recipe
I have had this annoyance with ModelMommy for a while but I can't figure out how to do this properly. 我对ModelMommy有一段时间的烦恼,但我无法弄清楚如何正确地做到这一点。
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的组织作为asset2的make方法的参数来解决:
>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make(organization=asset1.organization)
But there has to be a simpler, more clean way of doing this. 但是必须有一种更简单,更干净的方法。
EDIT 编辑
Based on the link in Helgi's answer I've changed all my recipe foreign keys to point to a closure: 基于Helgi的答案中的链接,我已将所有配方外键更改为指向闭包:
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')
And can create as many assets as I like: 并且可以创建尽可能多的资产:
>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make()
This doesn't seem to be possible (at least for now) but this feature has been discussed. 这似乎不可能(至少目前为止),但已讨论过此功能。 See here: Reference to same foreign_key object
请参见此处: 引用相同的foreign_key对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.