2013-08-26 29 views
2

我有一個tests.py,看起來像這樣:Django的動態夾具外鍵自

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) 

我一個人的模型是這樣的:

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

當我運行測試,我得到如下:

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

如何創建具有一個外鍵指向本身django_dynamic_fixture對象?

回答

0

據我瞭解函式N不分配ID,因爲它不是在數據庫中產生,也許這就是原因所在:

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

希望這將解決您的問題..

編輯

我想通了,你需要自我引用領域提供空=真,使其工作,這是有道理的,因爲自我引用必須在某個地方結束。

+0

感謝您的信息 - 我終於明白了原因,但我不確定如何解決此問題。 – Trewq

+0

@Trewq我已更新我的回答 – mariodev

+0

自引用必須爲null = True。另外,請檢查「number_of_laps」屬性。這對於這種關係來說非常完美。 (http://django-dynamic-fixture.readthedocs.org/en/latest/data.html#number-of-laps) –