Self referencing models initialization

211 views
Skip to first unread message

Santiago Palacio Gómez

unread,
Mar 13, 2014, 1:34:56 AM3/13/14
to django...@googlegroups.com
Hi everyone,

I'm a Django newbie, and I was following the tutorial for 1.6, creating a new app where one of the models is self-referencing. They ask to, in manage.py shell, create an instance of the model. But, as my model has a self reference foreign key, I can't pass any object to the key. I also would not like to leave it Nullable, as it may cause errors. Rather, I'd just like to pass 'self' as the reference, this is, the key it references should be its self key.

Is it possible? Thanks in advance!

Erik Cederstrand

unread,
Mar 13, 2014, 4:41:05 AM3/13/14
to Django Users
What is meant in the tutorial is most definitely not that the model ‘instance’ should reference itself, but rather that the instance should reference another instance of the same type, i.e. a parent-child relationship. Something like:

class Person(models.Model):
mother = models.ForeignKey(’self', null=True)
father = models.ForeignKey(’self', null=True)

You need to keep the field nullable because something must be root of the relationship structure (unless you want to create only cyclic relationships, which is not recommended for family structures...). To create a relationship do this:

eve = Person.objects.create()
adam = Person.objects.create()
abel = Person.objects.create(mother=eve, father=adam)


Erik

Santiago Palacio Gómez

unread,
Mar 13, 2014, 1:07:11 PM3/13/14
to django...@googlegroups.com
Ok, just did that and it worked (had to delete and re-create the db). Thank you very much for your quick reply.

One last question though, just for curiosity, is there no way to create such cyclic relationships? If so, how?

Shawn Milochik

unread,
Mar 13, 2014, 1:35:48 PM3/13/14
to django...@googlegroups.com
On Thu, Mar 13, 2014 at 1:07 PM, Santiago Palacio Gómez <spal...@gmail.com> wrote:
Ok, just did that and it worked (had to delete and re-create the db). Thank you very much for your quick reply.

One last question though, just for curiosity, is there no way to create such cyclic relationships? If so, how?

You can always make a relationship cyclical after the fact by just populating the foreign key field. You just can't have it required, because then you have a chick-and-egg problem. It's possible you could make it work by deferring the commit using commit=False [1], but overall it's probably a bad idea.

Santiago Palacio Gómez

unread,
Mar 13, 2014, 2:57:08 PM3/13/14
to django...@googlegroups.com, Sh...@milochik.com
I see, nice tip. Thanks!
Reply all
Reply to author
Forward
0 new messages