django-dynamic-fixture foreign key to self

788 Views Asked by At

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?

1

There are 1 best solutions below

2
On

From what I understand N function doesn't assign id, since it's not generated in db, maybe that is the reason:

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

Other thing, instead

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

you should do

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

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

Hopefully this will solve your issue..

EDIT

I just figured out, that you need to provide null=True to self referenced field, to make it work, which makes sense, since self reference must end somewhere.