Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a ForeignKey, NON NULL constraint failed

Tags:

python

django

I'm writing a website in Django, and I want to have different blogs for different categories of posts. I have a model Post, which uses a ForeignKey to the Blog model.

Following the useful help I was given here, I have:

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
    # ...

Whenever I try python manage.py migrate pad I get

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

Do I have to set an id in Blog explicitly? I tried with different combinations of blank=null and null=True in different fields, but I always get this error.

like image 524
mmcasetti Avatar asked Nov 11 '14 12:11

mmcasetti


Video Answer


2 Answers

In lieu of a response from OP, the advised solution in this case is to ensure you have cleaned out any lingering migrations by rebuilding/making migrations from the fresh copy of the model using the following:

python manage.py makemigrations pad

In this case remember that pad refers to the users application name. You can leave it off of the command to make fresh migrations across the board:

python manage.py makemigrations

Once complete you can run either the app-specific or general migration:

#Specific for this case
python manage.py migrate pad
#or Rebuild all available migrations
python manage.py migrate

If, after this, you are still having a problem then your model itself has an issue.

like image 57
Raymond Berg Avatar answered Oct 18 '22 11:10

Raymond Berg


I had exactly the same issue, and fixed it by adding blank=True when specifying the foreignkey, as suggested in this thread

Hope that helps..

like image 43
IonicBurger Avatar answered Oct 18 '22 12:10

IonicBurger