我在做一个笔记应用程序。当我尝试创建一个外键来链接用户及其注释时,我在使用
python manage.py migrate。我对外键非常陌生,我看了Django的文档,这就是他们是如何创建外键的。
下面是代码:
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.body[0:50]以下是错误:
django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id发布于 2021-10-30 08:30:03
您的问题是,数据库中存在没有author_id字段的现有注释,但您没有设置默认值,也不允许将其保留为空白。因此,添加字段是一个IntegrityError。
您可以通过两种方法解决这一问题:
允许字段为空
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)为字段设置默认值
models.User.objects.all().first()或为现有notes选择其他"defalt“作者models.User.objects.all().first()还可以通过从数据库中删除所有现有注释来解决此问题。
https://stackoverflow.com/questions/69777928
复制相似问题