外键和IntegrityError:id可能不为空 [英] Foreign keys and IntegrityError: id may not be NULL
本文介绍了外键和IntegrityError:id可能不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Fluff(models.Model):
#....
#一些字段定义
class Something(models.Model):
name = models.CharField(max_length = 200)
fluff = models.ForeignKey(Fluff)
syncdb
按预期进行,然后我去到shell来测试东西:
>>> s = Something()
>>> s.name ='Blah'
>>> s.fluff = Fluff(...)
>>>> s.save()
追溯(最近的最后一次调用):#traceback略过简单
IntegrityError:app_something.fluff_id可能不为空
我希望Django做出其魔法,找出绒毛
不保存,然后在保存之前保存取值
。这没有发生,但没关系,我可以自己保存绒毛
,让我们再试一次:
>>> s = Something()
>>> s.name ='Blah'
>>> s.fluff = Fluff(...)
>>>> s.fluff.save()
>>> s.save()
追溯(最近的最后一次调用):#traceback略过简单
IntegrityError:app_something.fluff_id可能不为空
没有运气。这应该是微不足道的,但我现在不能弄清楚。任何帮助将不胜感激。
解决方案
尝试这样做:
>>> s.name ='Blah'
>>> obj = Fluff(...)
>>>> obj.save()
>>>> s.fluff = obj
>>>> s.save()
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.
解决方案
Try to do something like this:
>>> s.name = 'Blah'
>>> obj = Fluff(...)
>>> obj.save()
>>> s.fluff = obj
>>> s.save()
这篇关于外键和IntegrityError:id可能不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文