对于ID> 3的用户使用SQLFORM时,尽管已引用了web2py的引用表中的记录,但仍存在外键约束

时间:2018-12-12 18:17:24

标签: web2py

我收到“外键约束失败”错误。我在引用表中有记录。这种情况仅适用于已登录的用户。它对于ID <= 3的用户有效,但对其他用户则无效。

这是相关的db.py代码:

    db.define_table('Roles',    
            Field('person', db.auth_user),    
            Field('role'))    
    db.define_table('Doctors',
            Field('doctor', db.auth_user, required = True),    
            Field('age', 'integer', required = True),    
            Field('qualification'),    
            Field('specialization'),    
            format = '%(doctor)s'    
            )    

    db.define_table('Patients',    
            Field('patient', db.auth_user, required = True),    
            Field('age', 'integer', required = True),    
            Field('doctor', db.Doctors, required = True),     
            Field('temperature', 'double'),     
            Field('blood_pressure', 'double'),     
            Field('haemoglobin', 'double'),     
            Field('contact_name'),     
            Field('contact_phone', 'bigint'),     
            format = '%(patient)s'     
           )     

    db.define_table('Assignments',     
            Field('doctor', 'reference Doctors', unique = False),     
            Field('patient', 'reference Patients', unique = False))     

这是相关的default.py代码:

def registerRole():    
role = int(request.args[0])    
form = FORM()    
if role == 1:    
    form = SQLFORM(db.Doctors).process()    
elif role == 2:    
    form = SQLFORM(db.Patients).process()    
if form.accepted:    
    response.flash = 'form accepted'    
    if role == 1:    
        db.Roles.insert(person = auth.user.id, role = 'doctor')
            auth.add_membership(auth.id_group('doctor'),auth.user.id)
        elif role == 2:
            i = 1
           db.Assignments.insert(doctor = int(form.vars.doctor), patient = auth.user.id)    
         db.Roles.insert(person = auth.user.id, role = 'patient')    
         auth.add_membership(auth.id_group('patient'),auth.user.id)    
     redirect(URL('index'))    
else:    
    response.flash = form.errors    
return dict(form = form, role = role)    

请帮助我解决此问题。我已经坚持了一段时间。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

db.Assignments.insert(doctor = int(form.vars.doctor), patient = auth.user.id)

上面,您将patient的值设置为auth.user.id,这是id表中的auth_user。但是,patient的{​​{1}}字段必须是Assignments表中的id,因为它的类型为Patients。相反,您可能希望使用reference Patients中的表格刚刚插入id中的记录Patients

form.vars.id

此外,请考虑db.Assignments.insert(doctor = int(form.vars.doctor), patient = form.vars.id) 始终是当前登录用户的auth.user.id。尚不清楚您对id的其他用法是否合适(即使用auth.user.iddb.Roles.insert),因为以表格形式选择为医生或患者的用户不一定会是登录用户。