简体   繁体   English

在peewee中创建新模型实例时,如何修复“无法添加或更新子行:外键约束失败”

[英]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. 我已经检查过userTd是否有UserId。 Here is the content of the userTable: 这是userTable的内容:

{ "ID": 1, "UserId": "001201400047", "UserName": "User A", "UserPass": "admin", "UserStatus": "admin" }, {“ID”:1,“UserId”:“001201400047”,“UserName”:“用户A”,“UserPass”:“admin”,“UserStatus”:“admin”},

{ "ID": 2, "UserId": "100100010000", "UserName": "User B", "UserPass": "user", "UserStatus": "student" } {“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 ))'). 我预计会有里面Attendancetable一个新的模型实例,但实际产量peewee.IntegrityError:(1452,“不能添加或更新子行,外键约束失败( AASattendanceTable ,约束fk_attendanceTable_1外键( UserId )参考userTableuserid ))')。

EDITED : I tried to change the x values into string,the problem remained the same. 编辑 :我试图将x值更改为字符串,问题保持不变。 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`))')

The leading zeros of x aren't being preserved when you convert them to a string on the next line. 当您将x转换为下一行的字符串时, x的前导零不会被保留。 The row insertion fails because "1201400047" is not in ["001201400047", "100100010000"] 行插入失败,因为"1201400047"不在["001201400047", "100100010000"]

str(x).zfill(USER_ID_WIDTH) may be a solution str(x).zfill(USER_ID_WIDTH)可能是一个解决方案

The model class indicates the fk is from Attendancetable.userid -> Usertable.id 模型类表示fk来自Attendancetable.userid - > Usertable.id

The db constraint indicates the foreign key is from Attendancetable.userid -> Usertable.userid db约束表示外键来自Attendancetable.userid - > Usertable.userid

Probably need to fix the model definition so the FK is pointing to the right column: 可能需要修复模型定义,以便FK指向右列:

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. 所以你可能需要稍微清理一下。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误1452(23000):无法添加或更新子行:外键约束失败我无法修复 - ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails That I can't fix Python Sqlalchemy mysql“无法添加或更新子行:外键约束失败” - Python Sqlalchemy mysql “Cannot add or update a child row: a foreign key constraint fails” 无法添加或更新子行:Django生成的MySQL表上的外键约束失败 - Cannot add or update a child row: a foreign key constraint fails on a Django generated MySQL table IntegrityError(1452,'无法添加或更新子行:外键约束失败) - IntegrityError (1452, 'Cannot add or update a child row: a foreign key constraint fails) django.db.utils.IntegrityError: (1452, '无法添加或更新子行:外键约束失败 - django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails Python 插入 MySQL:无法记录价格 1452 (23000):无法添加或更新子行:外键约束失败 - Python insert to MySQL : Failed to record Price 1452 (23000): Cannot add or update a child row: a foreign key constraint fails 无法删除或更新父行:外键约束失败 SQL 错误 - Cannot delete or update a parent row: a foreign key constraint fails SQL error IntegrityError: (1451, &#39;无法删除或更新父行:外键约束失败 (..)) - IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (..)) (pymysql.err.IntegrityError)(1451,&#39;无法删除或更新父行:外键约束失败...&#39;) - (pymysql.err.IntegrityError) (1451, 'Cannot delete or update a parent row: a foreign key constraint fails…') in Flask Django rest框架外键约束失败创建模型 - Django rest framework foreign key constraint fails creating model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM