繁体   English   中英

使用ForeignKey,NON NULL约束失败

[英]Using a ForeignKey, NON NULL constraint failed

我正在用Django写一个网站,而且我想为不同类别的帖子提供不同的博客。 我有一个模型Post,它使用Blog模型的ForeignKey。

继有益的帮助我得到了在这里 ,我有:

class Blog(models.Model):
    # category of the blog
    category = models.CharField(max_length=50)
    # its title (for the view)
    title = models.CharField(max_length=100)
    # its url (for url.py)
    url = models.URLField()

class Post(models.Model):
    # blog
    blog = models.ForeignKey(Blog, null=True)
    # other fields
    # ...

每当我尝试python manage.py migrate pad我都会得到

sqlite3.IntegrityError: NOT NULL constraint failed: pad_post__new.blog_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):

[...]

django.db.utils.IntegrityError: NOT NULL constraint failed: pad_post__new.blog_id

我是否必须在Blog中明确设置id 我尝试在不同的字段中使用blank=nullnull=True不同组合,但总是收到此错误。

代替OP的答复,在这种情况下,建议的解决方案是通过使用以下方法从模型的新副本中重建/进行迁移,以确保您清除了所有挥之不去的迁移:

python manage.py makemigrations pad

在这种情况下,请记住pad指的是用户应用程序名称。 您可以不使用命令来进行全面迁移:

python manage.py makemigrations

完成后,您可以运行特定于应用程序的迁移或常规迁移:

#Specific for this case
python manage.py migrate pad
#or Rebuild all available migrations
python manage.py migrate

如果在此之后您仍然遇到问题,则您的模型本身就有问题。

我有完全相同的问题,并通过在指定外键时添加blank = True来解决此问题,如本线程中所示

希望有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM