0

I copied a json file from online. I'm using it for django project. I entered the following lines in cmd -

>>> import json
>>> from blog.models import Post
>>> with open('posts.json') as f:
...   posts_json=json.load(f)
...
>>> for post in posts_json:
...   post = Post(title=post['title'], content=post['content'], author_id=post['
user_id'])
...   post.save()
...

And the error I got was -

Traceback (most recent call last):
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\sqlite3\base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: FOREIGN KEY constraint failed

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<console>", line 3, in <module>
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\base.py", line 745, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\base.py", line 782, in save_base
    updated = self._save_table(
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\base.py", line 887, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields
, raw)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\base.py", line 924, in _do_insert
    return manager._insert(
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\models\sql\compiler.py", line 1391, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._e
xecute)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang
o\db\backends\sqlite3\base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: FOREIGN KEY constraint failed

This is my models.py file -

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    title=models.CharField(max_length=100)
    content=models.TextField()
    date_posted=models.DateTimeField(default=timezone.now)
    author=models.ForeignKey(User,on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail',kwargs={'pk':self.pk})

This is the json file I copied from online https://raw.githubusercontent.com/CoreyMSchafer/code_snippets/master/Django_Blog/snippets/posts.json

4
  • Are you sure there exists a user with the id that you pass as author_id? Commented Apr 23, 2020 at 17:44
  • You don't need to tag your coding editor unless your question is specifically about the editor itself. Commented Apr 23, 2020 at 17:48
  • @MattDMo Are u saying about the tag sqlite? Commented Apr 24, 2020 at 13:29
  • @Gagankaranth no, about Sublime Text. Your question doesn't have anything to do with Sublime itself, so you don't need to tag it. Commented Apr 29, 2020 at 16:46

2 Answers 2

1

This is a later reply but maybe it will help someone else in the future.

I had the same issue now and the same code and posts.json as well, it seems that in posts.json the user_id it either 1 or 2 so the error means that there is no user with id 1 or 2 in your database.

I would say that there is no user with id = 2 I supposed you have created a superuser which is id = 1 and if you create a second user it may not take id = 2, so you need to find out what is that id and change it in your posts.json file.

That's how I just fixed my problem.

Sorry for my English.

Sign up to request clarification or add additional context in comments.

Comments

0

The only foreign key here is author, so a foreign key constraint failing must mean that there's no user with an id corresponding to the user_id field in a record in that data.

Since by a quick glance it looks like there's only user ids 1 and 2, make sure you have those two users in your database, then try again.

1 Comment

So, what to do here? Should we remove author?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.