[英]Using a ForeignKey, NON NULL constraint failed
我正在用Django寫一個網站,而且我想為不同類別的帖子提供不同的博客。 我有一個模型Post,它使用Blog模型的ForeignKey。
繼有益的幫助我得到了在這里 ,我有:
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=null
和null=True
不同組合,但總是收到此錯誤。
代替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
如果在此之后您仍然遇到問題,則您的模型本身就有問題。
我有完全相同的問題,並通過在指定外鍵時添加blank = True來解決此問題,如本線程中所示
希望有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.