Foreign keys and IntegrityError: id may not be NULL
Django newbie here. I have two simple models like this:
class Fluff(models.Model):
# ....
# some fields definitions
class Something(models.Model):
name = models.CharField(max_length=200)
fluff = models.ForeignKey(Fluff)
syncdb
goes as expected, and then I go to the shell to test things:
>>> s = Something()
>>> s.name = 'Blah'
>>> s.fluff = Fluff(...)
>>> s.save()
Traceback (most recent call last): # traceback skipped for brevity
IntegrityError: app_something.fluff_id may not be NULL
I expected Django to do its magic, figure out fluff
is not saved, then save it before saving s
. That didn't happen, but it's OK, I can sav开发者_如何学JAVAe fluff
for myself, let's try again:
>>> s = Something()
>>> s.name = 'Blah'
>>> s.fluff = Fluff(...)
>>> s.fluff.save()
>>> s.save()
Traceback (most recent call last): # traceback skipped for brevity
IntegrityError: app_something.fluff_id may not be NULL
No luck. This should be trivial, but I cannot figure it out at the moment. Any help would be appreciated.
Try to do something like this:
>>> s.name = 'Blah'
>>> obj = Fluff(...)
>>> obj.save()
>>> s.fluff = obj
>>> s.save()
精彩评论