[英]FOREIGN KEY constraint failed with Custome Model in Django
[英]NOT_NULL contraint failed when adding foreign key to model in django
我正在制作一個筆記應用程序。 當我嘗試創建一個外鍵來鏈接用戶及其筆記時,我在使用時遇到錯誤
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
您的問題是數據庫中存在沒有author_id
字段的現有注釋,但您沒有設置默認值,也不允許保留為空白。 因此,添加該字段是一個IntegrityError
。
您可以通過兩種方式解決此問題:
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
models.User.objects.all().first()
或其他一些現有筆記的“默認”作者migrate
您還可以通過從數據庫中刪除所有現有筆記來解決問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.