我正在制作一個筆記應用程式。當我嘗試創建一個外鍵來鏈接用戶及其筆記時,我在使用時遇到錯誤
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
uj5u.com熱心網友回復:
您的問題是資料庫中存在沒有author_id欄位的現有注釋,但您沒有設定默認值,也不允許保留為空白。因此它是一個IntegrityError添加欄位。
您可以通過兩種方式解決此問題:
允許欄位為空
- 洗掉遷移檔案夾中的最后一次遷移
- 像這樣編輯作者欄位:
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
- 運行 makemigrations 并遷移
為欄位設定默認值
- 從遷移檔案夾中洗掉最后一次遷移。您也可以編輯它,但簡單地洗掉它是最簡單的
- 再次運行 makemigrations
- 在 make 遷移期間,它會提示您是否要為該欄位提供默認值。選擇“現在提供一個值”
models.User.objects.all().first()為現有筆記鍵入或其他一些“默認”作者- 跑
migrate
您還可以通過從資料庫中洗掉所有現有筆記來解決問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/343305.html
上一篇:/login/userlogin()處的型別錯誤采用1個位置引數,但給出了2個
下一篇:django資料庫查詢OR條件
