开发者

Django model - field_id is None, even though field is not None, getting an error as a result

I'm getting an error I don't understand with Django 1.3 about an object member being null. That member isn't a field, it is the id for a field.

Here's the code.

The model:

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

The error:

IntegrityError: mainapp_directorsindividual.director_id may not be NULL

The code that creates the object:

link = DirectorsIndividual(company = co,
                           individual = indiv开发者_如何学Pythonidual,
                           director = officer)

The state of the object (irrelevant fields omitted):

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

What's happening here? Why is the DirectorsIndividual object not picking up the id of the director object assigned to it?

[Edit: more object info]


Double-check the order in which you are assigning and saving the objects. Here's a super-reduced example:

from django.db import models

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

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

This will cause the integrity violation:

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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜