小编Bja*_*son的帖子

模范妈妈:多个食谱与单个食谱有外键关系

我对 ModelMommy 的这种烦恼已经有一段时间了,但我不知道如何正确地做到这一点。

让我们假设一个简单的关系:

class Organization(models.Model):
    label = models.CharField(unique=True)

class Asset(models.Model):
    organization = models.ForeignKey(Organization)
    label = models.CharField(unique=True)
Run Code Online (Sandbox Code Playgroud)

和食谱:

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')
Run Code Online (Sandbox Code Playgroud)

现在,当我制作这些资产配方时,我收到错误:

>> 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.
Run Code Online (Sandbox Code Playgroud)

这可以通过将 asset1 的组织作为参数提供给 asset2 的 make 方法来解决:

>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make(organization=asset1.organization)
Run Code Online (Sandbox Code Playgroud)

但必须有一种更简单、更干净的方法来做到这一点。

编辑 …

testing django model-mommy

5
推荐指数
1
解决办法
1634
查看次数

标签 统计

django ×1

model-mommy ×1

testing ×1