【问题标题】:Model Mommy: Multiple recipes with foreign key relation to a single recipeModel Mommy:与单个食谱具有外键关系的多个食谱
【发布时间】:2016-08-23 10:21:54
【问题描述】:

我对 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)

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

编辑

根据 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')

并且可以创建任意数量的资产:

>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make()

【问题讨论】:

    标签: django testing model-mommy


    【解决方案1】:

    这似乎是不可能的(至少现在是这样),但这个功能已经被讨论过了。见这里:Reference to same foreign_key object

    【讨论】:

      猜你喜欢
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多