Я хочу добавить новый экземпляр модели в таблицу, но он всегда показывает «Невозможно добавить или обновить дочернюю строку: ограничение внешнего ключа не выполнено».
Я уже проверяю, есть ли у userTable UserId или нет. Вот содержимое таблицы пользователя:
{"ID": 1, "UserId": "001201400047", "UserName": "Пользователь 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()
Я ожидаю, что внутри Attendancetable будет новый экземпляр модели, но фактический вывод - peewee.IntegrityError: (1452, 'Невозможно добавить или обновить дочернюю строку: ограничение внешнего ключа не выполняется (AAS
. attendanceTable
, CONSTRAINT fk_attendanceTable_1
ИНОСТРАННЫЙ КЛЮЧ (UserId
) ССЫЛКИ userTable
(userid
)) ').
EDITED :
Я пытался изменить значения х в строку, проблема осталась прежней.
Ниже приведено полное сообщение об ошибке:
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`))')