2

I have a tests.py that looks like this:

from django_dynamic_fixture import G,N
from person.models import Person
from django.test import TestCase

class EmailSendTests(TestCase):
    def test_send_email(self):
        person = N(Person)

My Person model looks like this:

class Person(models.Model):
    person_no = models.IntegerField(primary_key=True)
    address =  models.ForeignKey('Address', db_column = 'address_no')
    guarantor = models.ForeignKey('Person', db_column = 'gperson_no')

When I run the tests, I get the following:

ValueError: Cannot assign None: "Patient.guarantor" does not allow null values.

How do I create a django_dynamic_fixture object that has a foreignkey pointing to itself?

4

1 回答 1

0

据我了解,N 函数没有分配 id,因为它不是在 db 中生成的,也许这就是原因:

https://github.com/paulocheque/django-dynamic-fixture/wiki/Documentation#wiki-n

其他的,而不是

guarantor = models.ForeignKey('Person', db_column = 'gperson_no')

你应该做

guarantor = models.ForeignKey('self', db_column = 'gperson_no')

https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey

希望这能解决你的问题..

编辑

我刚刚发现,您需要为自引用字段提供 null=True 以使其工作,这是有道理的,因为自引用必须在某个地方结束。

于 2013-08-26T18:03:53.473 回答