Using the ForeignKey parameter, NON NULL constraint failed

I am writing a website in Django and I want to have different blogs for different categories of posts. I have a Post model that uses the ForeignKey model for a blog.

After helpful 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 

Should I set the blog id explicitly? I tried with various combinations of blank=null and null=True in different fields, but always get this error.

+5
source share
2 answers

Instead of a response from OP, the recommended solution in this case is to make sure that you clear any lingering migrations by restoring / making migrations from a new copy of the model using the following:

 python manage.py makemigrations pad 

In this case, remember that pad refers to the user's application name. You can leave it outside the team to make fresh migrations in all directions:

 python manage.py makemigrations 

After completion, you can either transfer the application or the general transfer:

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

If after this you still have a problem, your model has a problem.

+1
source

I had exactly the same problem, and I fixed it by adding blank = True when specifying a foreign key, as suggested in this thread

Hope this helps.

0
source

Source: https://habr.com/ru/post/1206629/


All Articles