I've got a model which, when saved, should create and save one of its foreign keys if it doesn't already exist:
class MyModel(m.Model):
fk = m.ForeignKey(AnotherModel)
def save(self):
if not self.fk_id:
self.fk = AnotherModel()
self.fk.save()
return super(MyModel, self).save()
But the call to super(MyModel, self).save()
raises an error, because self.fk_id
is still null:
Traceback (most recent call last): ... File ".../models.py", line 10, in save return super(MyModel, self).save() ... File ".../django/db/backends/postgresql_psycopg2/base.py", line 44, in execute return self.cursor.execute(query, args) IntegrityError: null value in column "fk_id" violates not-null constraint
Note: a debugger shows that self.fk.id
has been set correctly, and everything seems to work when self.fk_id = self.fk.id
is added.
So, my question: why is self.fk_id = self.fk.id
necessary? And is it possible to avoid doing that explicitly?
I think this bug report is your answer. Currently, you just need to set the related object after it has a primary key itself. They're still discussing the patch.