在Peewee中创建新模型实例时,如何解决“无法添加或更新子行:外键约束失败”的问题

时间:2019-04-04 23:55:51

标签: python peewee

我想在表中添加新的模型实例,但是它始终显示“无法添加或更新子行:外键约束失败”。

我已经检查过userTable是否具有UserId。这是userTable的内容:

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

{“ ID”:2,“ UserId”:“ 100100010000”,“ UserName”:“用户B”,“ UserPass”:“用户”,“ UserStatus”:“学生”}

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。{{1 }},约束attendanceTable外键(fk_attendanceTable_1)参考UserIduserTable))')。

已编辑: 我试图将x值更改为字符串,问题仍然存在。 下面是完整的错误消息:

userid

2 个答案:

答案 0 :(得分:0)

x的前导零转换为下一行的字符串时,不会保留它们。 行插入失败,因为"1201400047"不在["001201400047", "100100010000"]

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

答案 1 :(得分:0)

模型类指示fk来自Attendancetable.userid-> Usertable.id

数据库约束指示外键来自Attendancetable.userid-> Usertable.userid

可能需要修复模型定义,以便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)

看起来您先前存在的架构可能有点混乱。因此,您可能需要清理一些东西。