使用ForeignKey,非空约束失败

2024-04-27 02:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Django写一个网站,我想有不同的博客不同类别的文章。我有一个模型帖子,它使用了博客模型的外键。

在得到有用的帮助后,我得到了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的不同组合,但是我总是得到这个错误。


Tags: ofthe模型idurlmodelmodelsblog
2条回答

在这种情况下,建议的解决方案是,使用以下方法从模型的新副本重建/进行迁移,以确保清除了任何延迟迁移:

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

如果在这之后,您仍然有问题,那么您的模型本身就有问题。

我遇到了完全相同的问题,并在指定foreignkey时添加blank=True来解决这个问题,如建议的in this thread

希望能帮上忙。。

相关问题 更多 >