使用外键,NOT NULL约束失败

时间:2014-11-11 12:52:02

标签: python django

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

在我得到here的有用帮助后,我有:

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的不同组合,但我总是遇到此错误。

2 个答案:

答案 0 :(得分:1)

代替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

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

答案 1 :(得分:1)

我有完全相同的问题,并在指定外键时通过添加blank = True来修复它,如建议in this thread

希望有所帮助..

相关问题