How can I make a ForeignKey refer back to the object itself? I’m trying :
Alias(MyBaseModel):
type = models.ForeignKey('self')
a = Alias()
a.type = a
a.save()
But then when I run it :
(1048, "Column 'type_id' cannot be null")
I don’t want the type to be null, I want it to contain its own ID. I have tons of objects, but only 1 loops back to itself, so I really don’t want tot make it null. Ideas?
The problem is that when you did
a.type = a, a did not yet exist in the database, therefore it has no pk.One way around this is to save twice, first to save it into the database, referring to a dummy object that’s already in the database, then save it again once you can get it from the database. One problem with this is there’s sort of a chicken and egg problem of actually getting such an object into the database in the first place. I’d deal with this by means of creating a fixture to run each time you use sync-db, so that one such object exists and is valid.
Another option is to relax the not-null constraint and be diligent about getting them assigned.
Either way, inserting into such a table will always be a pain because you can’t get the PK to use without first inserting, and you can’t insert without having a key to use in the reference field, regardless of ORM or database or anything.
an alternative solution is to break the circular dependency and do something like:
You can still get useful information by using django’s very smart accessors,
which can get you back to the original Alias object without having an explicit link to it.