2015-05-28 165 views
2

我正在构建一个使短网址的服务。我有型号:Django模型完整性错误:NOT NULL约束失败:

from django.db import models 

class ShortURL(models.Model): 
    url = models.CharField(max_length = 50) 

class LongURL(models.Model): 
    name = models.CharField(max_length = 100, null=True) 
    url_to_short = models.ForeignKey(ShortURL) 

我已经运行以下命令:python manage.py migrate 如果我打开解释,使用python manage.py shell并运行此代码:

>>> from appshort.models import LongURL 
>>> a = LongURL(name = 'hello_long_link') 
>>> a.save() 

然后我得到的错误:

django.db.utils.IntegrityError: NOT NULL constraint failed: appshort_longurl.url_to_short_id

我做错了什么?

+1

'url_to_short' FK字段是需要在您的模型,但你忘了填写它。 – danihp

+2

你创建一个'LongURL'而不给它一个'ShortURL',这是一个错误。如果这是一个有效的情况,请按照以下所述使ShortURL字段可选:https://stackoverflow.com/questions/6619984/can-i-make-the-foreign-key-field-optional-in-django-model – l4mpi

回答

4
class LongURL(models.Model): 
    name = models.CharField(max_length = 100, null=True) 
    url_to_short = models.ForeignKey(ShortURL) 

你已经设置它的方式,url_to_short外键是不可选。所以,当你试图保存:

>>> a = LongURL(name = 'hello_long_link') 
>>> a.save() 

Django是想告诉你,你没有提供你a模型实例的url_to_short关系。

你要么需要

  • 提供的SHORTURL关系,当您创建LongURL实例
  • 充分利用url_to_short关系可选的null=True, blank=True
+0

这是特别令人困惑的,因为我有另外一个例子,其中'default = None'在相同的情况下工作,但现在似乎需要(?)'null = True,blank = True'。 – szeitlin

相关问题