Django makemigrations works, migrate fails with “django.db.utils.IntegrityError: NOT NULL constraint failed”

[亡魂溺海] 提交于 2021-02-18 11:29:09

问题


I'm stuck. Django 1.7, SQLite3.

I've changed my model to add the thumbnail column, as in this tutorial. It was this:

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField('date published')
    likes = models.IntegerField(default=0)

    def __str__(self):
        return  self.title

and is now this:

from django.db import models
from time import time         

def get_upload_file_name(instance, filename):
    return  "uploaded_files/%s_%s" % (str(time()).replace(".", "_"), filename)

class Article(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField('date published')
    likes = models.IntegerField(default=0) 
    thumbnail = models.FileField(upload_to=get_upload_file_name, null=True)

    def __str__(self):
        return  self.title

I backed up all data to a json text file with

python manage.py dumpdata article --indent=4 > article.json

and then executed

python manage.py makemigrations

which worked. But

python manage.py migrate

fails with

django.db.utils.IntegrityError: NOT NULL constraint failed: article_article__new.thumbnail

And now, even after adding null=True to the thumbnail line in models.py, running makemigrations succeeds, and migrate fails the same way.

What do I do?


回答1:


My app name (as created with python manage.py startapp) is called articles. Here is the new articles\migrations folder, after getting the null-constraint error multiple times:

__init__.py
0001_initial.py
0002_auto_20140803_1540.py
0003_auto_20140803_1542.py
0004_auto_20140803_1450.py
0005_auto_20140803_1552.py
__pycache__
   __init__.cpython-34.pyc
   0001_initial.cpython-34.pyc
   0002_auto_20140803_1540.cpython-34.pyc
   0003_auto_20140803_1542.cpython-34.pyc
   0004_auto_20140803_1450.cpython-34.pyc
   0005_auto_20140803_1552.cpython-34.pyc

I deleted all the 000* files, in both directories, except 0001.

I then ran

python manage.py makemigrations

and

python manage.py migrate

successfully.

Thank goodness for irc.freenode.net/django.




回答2:


Just to add another solution.

In my case how i created BASE_DIR was not correct hence DATABASES NAME was also wrong. So it was creating the database at some other place. And when i was running migrations it was throwing this error propably because some old database existed there. So the fix was to just correct the DATABASE path.



来源:https://stackoverflow.com/questions/25109075/django-makemigrations-works-migrate-fails-with-django-db-utils-integrityerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!