Foreign keys and IntegrityError: id may not be NULL

天涯浪子 提交于 2020-01-04 11:43:12

问题


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


回答1:


Try to do something like this:

>>> s.name = 'Blah'
>>> obj = Fluff(...)
>>> obj.save()
>>> s.fluff = obj
>>> s.save()


来源:https://stackoverflow.com/questions/7215279/foreign-keys-and-integrityerror-id-may-not-be-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!