我有一个模型,在保存时,如果它还不存在,应该创建并保存其中一个外键:
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()
但是对super(MyModel, self).save()
的调用会引发错误,因为self.fk_id
仍为空:
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
注意:调试器显示已正确设置self.fk.id
,并且在添加self.fk_id = self.fk.id
时似乎一切正常。
所以,我的问题:为什么self.fk_id = self.fk.id
是必要的?是否可以避免明确地这样做?