Search code examples
pythonpeewee

How to fix 'Cannot add or update a child row: a foreign key constraint fails' when creating new model instance in peewee


I want to add a new model instance in a table, but it always shows 'Cannot add or update a child row: a foreign key constraint fails'.

I already check if the userTable has the UserId or not. Here is the content of the userTable:

{ "ID": 1, "UserId": "001201400047", "UserName": "User A", "UserPass": "admin", "UserStatus": "admin" },

{ "ID": 2, "UserId": "100100010000", "UserName": "User B", "UserPass": "user", "UserStatus": "student" }

from peewee import *
from datetime import datetime

database = MySQLDatabase('AAS', **{'passwd': 'admin', 'charset': 'utf8', 'user': 'yusfa', 'use_unicode': True})

class UnknownField(object):
    def __init__(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = database

class Classtable(BaseModel):
    classid = CharField(column_name='ClassId', primary_key=True)
    lecturerid = ForeignKeyField(column_name='LecturerId', model=Lecturertable)
    roomid = ForeignKeyField(column_name='RoomId', model=Roomtable)
    subjectid = ForeignKeyField(column_name='SubjectId', model=Subjecttable)

    class Meta:
        table_name = 'classTable'

class Usertable(BaseModel):
    id = AutoField(column_name='ID')
    userid = CharField(column_name='UserId', unique=True)
    username = CharField(column_name='UserName', null=True)
    userpass = CharField(column_name='UserPass', null=True)
    userstatus = CharField(column_name='UserStatus', null=True)

    class Meta:
        table_name = 'userTable'

class Attendancetable(BaseModel):
    classid = ForeignKeyField(column_name='ClassId', model=Classtable, null=True)
    date = DateTimeField(column_name='Date', null=True)
    id = AutoField(column_name='ID')
    userid = ForeignKeyField(column_name='UserId', model=Usertable, null=True)

    class Meta:
        table_name = 'attendanceTable'

database.connect()

times = ' 7:30:00'
x = 001201400047
x_attended = Attendancetable.create(classid = 'IT_20141', date = str(datetime.now()).split(' ')[0] + times, userid = str(x))
x_attended.save()

database.close()

I expect there will be a new model instance inside Attendancetable but the actual output is peewee.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (AAS.attendanceTable, CONSTRAINT fk_attendanceTable_1 FOREIGN KEY (UserId) REFERENCES userTable (userid))').

EDITED: I tried to change the x values into string,the problem remained the same. Below is the full of error message:

Traceback (most recent call last):
  File "test6.py", line 93, in <module>
    x_attended = Attendancetable.create(classid = 'IT_20141', date = str(datetime.now()).split(' ')[0] + times, userid = x)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 5580, in create
    inst.save(force_insert=True)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 5727, in save
    pk_from_cursor = self.insert(**field_dict).execute()
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 1622, in inner
    return method(self, database, *args, **kwargs)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 1693, in execute
    return self._execute(database)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2355, in _execute
    return super(Insert, self)._execute(database)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2118, in _execute
    cursor = database.execute(self)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2724, in execute
    return self.execute_sql(sql, params, commit=commit)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2718, in execute_sql
    self.commit()
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2509, in __exit__
    reraise(new_type, new_type(*exc_args), traceback)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2711, in execute_sql
    cursor.execute(sql, params or ())
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 250, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
    raise errorvalue
peewee.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`AAS`.`attendanceTable`, CONSTRAINT `fk_attendanceTable_1` FOREIGN KEY (`UserId`) REFERENCES `userTable` (`userid`))')
Traceback (most recent call last):
  File "test6.py", line 93, in <module>
    x_attended = Attendancetable.create(classid = 'IT_20141', date = str(datetime.now()).split(' ')[0] + times, userid = x)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 5580, in create
    inst.save(force_insert=True)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 5727, in save
    pk_from_cursor = self.insert(**field_dict).execute()
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 1622, in inner
    return method(self, database, *args, **kwargs)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 1693, in execute
    return self._execute(database)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2355, in _execute
    return super(Insert, self)._execute(database)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2118, in _execute
    cursor = database.execute(self)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2724, in execute
    return self.execute_sql(sql, params, commit=commit)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2718, in execute_sql
    self.commit()
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2509, in __exit__
    reraise(new_type, new_type(*exc_args), traceback)
  File "/home/user/.local/lib/python2.7/site-packages/peewee.py", line 2711, in execute_sql
    cursor.execute(sql, params or ())
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 250, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
    raise errorvalue
peewee.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`AAS`.`attendanceTable`, CONSTRAINT `fk_attendanceTable_1` FOREIGN KEY (`UserId`) REFERENCES `userTable` (`userid`))')

Solution

  • The model class indicates the fk is from Attendancetable.userid -> Usertable.id

    The db constraint indicates the foreign key is from Attendancetable.userid -> Usertable.userid

    Probably need to fix the model definition so the FK is pointing to the right column:

    class Attendancetable(BaseModel):
        classid = ForeignKeyField(column_name='ClassId', model=Classtable, null=True)
        date = DateTimeField(column_name='Date', null=True)
        id = AutoField(column_name='ID')
        userid = ForeignKeyField(column_name='UserId', field='userid', model=Usertable, null=True)
    

    Looks like your pre-existing schema was a bit messy perhaps. So you might need to clean things up a bit.