Django模型 - field_id为None,即使字段不是None,结果也会出错

时间:2011-08-03 16:32:00

标签: django django-models

我收到一个错误我不明白Django 1.3关于一个对象成员为null。该成员不是字段,它是字段的id。

这是代码。

型号:

class DirectorsIndividual(models.Model):
     company = models.ForeignKey(CompanyUK)
     director = models.ForeignKey(Director)
     individual = models.ForeignKey(Individual)

错误:

IntegrityError: mainapp_directorsindividual.director_id may not be NULL

创建对象的代码

link = DirectorsIndividual(company = co,
                           individual = individual,
                           director = officer)

对象的状态(省略了不相关的字段):

link.director => <Director: Director object>
link.director_id => None
link.director.id => 3
link.individual => <Individual: Individual object>
link.individual.id => 2

这里发生了什么?为什么DirectorsIndividual对象没有获取分配给它的导演对象的id?

[编辑:更多对象信息]

1 个答案:

答案 0 :(得分:1)

仔细检查您分配和保存对象的顺序。这是一个超级简化的例子:

from django.db import models

class X(models.Model):
    name = models.CharField(max_length=80)

class Y(models.Model):
    x = models.ForeignKey(X)

这会导致完整性违规:

x = X()
y = Y()

x.name = 'test'
y.x = x # At this moment, the pk has not yet been assigned.

x.save() # Assigns the pk, but doesn't copy it over to the foreign key in y.
y.save() # Bang.