处理自我指涉外键; django搅拌机

时间:2016-03-20 15:01:52

标签: python django django-models django-testing

我得到了自我引用FK的典型运行时错误,用假对象测试django:

In [12]: from mixer.backend.django import mixer

In [13]: x = mixer.blend(ItemGroup)


/home/cchilders/.virtualenvs/clientsite/lib/python3.4/site-packages/django/db/models/fields/related.py in __set__(self, instance, value)
    587             raise ValueError(
    588                 'Cannot assign None: "%s.%s" does not allow null values.' %
--> 589                 (instance._meta.object_name, self.field.name)
    590             )
    591         elif value is not None and not isinstance(value, self.field.rel.to):

ValueError: Mixer (<class 'clientsite.gacl.models.AroGroup'>): Cannot assign None: "AroGroup.parent" does not allow null values.

模特:

class ItemGroup(models.Model):
    parent = models.ForeignKey('self', db_column='parent_id')
    name = models.CharField(max_length=255)
    value = models.CharField(max_length=255, unique=True)

    class Meta:
        db_table = u'item_groups'

    def __str__(self):
        return self.value

    def __repr__(self):
        return '<{} {}: {}>'.format(self.__class__.__name__, self.pk, self.value)

在将自己称为FK时,文档很少。你怎么能用django混音器伪装一个需要的实例呢?谢谢

1 个答案:

答案 0 :(得分:1)

尝试将null=True添加到parent字段的声明中。必须至少有一个顶级ItemGroup不能拥有父母。