'Django Foreign Key error ......What should I do now?
```In [1]: import json
In [2]: from Bugijugi. models import Post
In [3]: with open('posts.json') as f:
...: posts_json = json.load(f)
...:
In [4]: for post in posts_json:
...: post = Post(title=post['title'], content=post['content'], author_id=post['us
...: er_id'])
...: post.save()
...: ```
--------------------------------------------------------------------------- IntegrityError Traceback (most recent call last) File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py:97, in DatabaseErrorWrapper.call..inner(*args, **kwargs) 96 with self: ---> 97 return func(*args, **kwargs)
IntegrityError: FOREIGN KEY constraint failed
The above exception was the direct cause of the following exception:
IntegrityError Traceback (most recent call last) Input In [4], in <cell line: 1>() 1 for post in posts_json: 2 post = Post(title=post['title'], content=post['content'], author_id=post['user_id']) ----> 3 post.save()
File F:\IMPORTANT\GAME\vrsty life\CSE 347\Project\Sample\Bugijugi\models.py:27, in Post.save(self) 26 def save(self): ---> 27 return super().save()
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:743, in Model.save(self, force_insert, force_update, using, update_fields) 740 if loaded_fields: 741 update_fields = frozenset(loaded_fields) --> 743 self.save_base(using=using, force_insert=force_insert, 744 force_update=force_update, update_fields=update_fields)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:780, in Model.save_base(self, raw, force_insert, force_update, using, update_fields) 778 if not raw: 779 parent_inserted = self._save_parents(cls, using, update_fields) --> 780 updated = self._save_table( 781 raw, cls, force_insert or parent_inserted, 782 force_update, using, update_fields, 783 ) 784 # Store the database on which the object was saved 785 self._state.db = using
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:885, in Model._save_table(self, raw, cls, force_insert, force_update, using, update_fields) 882 fields = [f for f in fields if f is not meta.auto_field] 884 returning_fields = meta.db_returning_fields --> 885 results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) 886 if results: 887 for value, field in zip(results[0], returning_fields):
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py:923, in Model._do_insert(self, manager, using, fields, returning_fields, raw) 918 def _do_insert(self, manager, using, fields, returning_fields, raw): 919 """ 920 Do an INSERT. If returning_fields is defined then this method should 921 return the newly created data for the model. 922 """ --> 923 return manager._insert( 924 [self], fields=fields, returning_fields=returning_fields, 925 using=using, raw=raw, 926 )
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py:85, in BaseManager._get_queryset_methods..create_method..manager_method(self, *args, **kwargs) 84 def manager_method(self, *args, **kwargs): ---> 85 return getattr(self.get_queryset(), name)(*args, **kwargs)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py:1301, in QuerySet._insert(self, objs, fields, returning_fields, raw, using, ignore_conflicts) 1299 query = sql.InsertQuery(self.model, ignore_conflicts=ignore_conflicts) 1300 query.insert_values(fields, objs, raw=raw) -> 1301 return query.get_compiler(using=using).execute_sql(returning_fields)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py:1448, in SQLInsertCompiler.execute_sql(self, returning_fields) 1446 elif self.connection.features.can_return_columns_from_insert: 1447
assert len(self.query.objs) == 1 -> 1448 rows = [self.connection.ops.fetch_returned_insert_columns( 1449 cursor, self.returning_params, 1450 )] 1451 else: 1452 rows = [(self.connection.ops.last_insert_id( 1453 cursor, opts.db_table, opts.pk.column, 1454 ),)]File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\operations.py:185, in BaseDatabaseOperations.fetch_returned_insert_columns(self, cursor, returning_params) 180 def fetch_returned_insert_columns(self, cursor, returning_params): 181 """ 182 Given a cursor object that has just performed an INSERT...RETURNING 183 statement into a table, return the newly created data. 184 """ --> 185 return cursor.fetchone()
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py:96, in DatabaseErrorWrapper.call..inner(*args, **kwargs) 95 def inner(*args, **kwargs): ---> 96 with self: 97 return func(*args, **kwargs)
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py:90, in DatabaseErrorWrapper.exit(self, exc_type, exc_value, tracebackn DatabaseErrorWrapper.exit(self, exc_type, exc_value, traceback) 88 if dj_exc_type not in (DataError, IntegrityError): 89 self.wrapper.errors_occurred = True ---> 90 raise dj_exc_value.with_traceback(traceback) from exc_value
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py:97, in DatabaseErrorWrapper.call..inner(*args, **kwargs) n DatabaseErrorWrapper.call..inner(*args, **kwargs) 95 def inner(*args, **kwargs): 96 with self: ---> 97 return func(*args, **kwargs)
IntegrityError: FOREIGN KEY constraint failed
Solution 1:[1]
Cause
author_id value is not a valid id of Author in the database. You need to create authors with ids matching values in the author_id field first before setting them in the Post model.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | annonymous |
