如何在peewee的多个表中创建记录?

时间:2018-12-25 11:36:46

标签: mysql python-2.7 database-design orm peewee

我对数据库驱动的应用程序和数据库ORM的了解很少,我已经在peewee https://codereview.stackexchange.com/q/210293/22943中编写了该模型

并且我希望能够使用“ Patient”表中“ Patient ID”的“ Relative”和“ PatientAttendOnVisit”外键同时更新3个表“ Patient”,“ Relative”和“ PatientAttendOnVisit”。

我直接尝试了

def add_patient_visit(data=None):
    """
    Adds new visit to clinic of patient 
    for new or follow up patient.
    """
    if not data:
        raise ValueError("Please pass the user info.")
    try:
        patient = _clinic.Patient.get(name=data["name"])
        if patient:
            print "Patient exists with same name."
        response_object = {
        "status": "fail",
        "message": "Patient already in record."
        }
        return response_object, 400
    except peewee.DoesNotExist as er:
        patient = _clinic.Patient.create(
            name=data["name"],
            townCity=data["townCity"],
            contactnumber=data["contactnumber"],
            age=data["age"],
            gender=data["gender"],
            email=data["email"],
            postalAddress=data["postalAddress"])
        relative = _clinic.Relative.create(relation=data["relation"],
            relativeName=data["relativeName"])

        attendence = _clinic.PatientAttendOnVisit.create(
            dateTimeofvisit=data["dateTimeofvisit"],
            attendtype=data["attendtype"],
            department=data["department"]
            )

但尝试这样做会给我以下错误:

  

返回controller.add_patient_visit(data = data)文件   “ /Users/ciasto/Development/python/clinic-backend/app/api/clinic/controller.py”,   第35行,在add_ Patient_visit中       relativeName = data [“ relativeName”])文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   创建中的第5580行       inst.save(force_insert = True)文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   5727行,保存       pk_from_cursor = self.insert(** field_dict).execute()文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   内线1622       返回方法(自身,数据库,* args,** kwargs)文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   第1693行,在执行       返回self._execute(数据库)文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   _execute中的第2355行       返回超级(插入,自我)。_execute(数据库)文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   _execute中的第2118行       cursor = database.execute(self)文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   行2724,在执行       返回self.execute_sql(sql,params,commit = commit)文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   第2718行,在execute_sql中       self.commit()文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   第2509行,退出       reraise(new_type,new_type(* exc_args),traceback)文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/peewee.py”,   第2711行,在execute_sql中       cursor.execute(sql,params或())文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/MySQLdb/cursors.py”,   第205行,在执行中       self.errorhandler(self,exc,value)文件“ /Users/ciasto/Development/python/clinic-backend/clinic_venv/lib/python2.7/site-packages/MySQLdb/connections.py”,   第36行,在defaultErrorhandler中       引发errorclass,errorvalue IntegrityError:(1452,'无法添加或更新子行:外键约束失败   ({clinic_backendrelative,约束relative_ibfk_1外键   ({patient_id)参考文献patientid))')

1 个答案:

答案 0 :(得分:0)

我发现没什么复杂的

def add_patient_visit(data=None):
    """
    Adds new visit to clinic of patient 
    for new or follow up patient.
    """
    if not data:
        raise ValueError("Please pass the user info.")
    patient = _clinic.Patient.create(
            name=data["name"],
            townCity=data["townCity"],
            contactnumber=data["contactnumber"],
            age=data["age"],
            gender=data["gender"],
            email=data["email"],
            postalAddress=data["postalAddress"])

        relative = _clinic.Relative.create(
            patient=patient,
            relation=data["relation"],
            relativeName=data["relativeName"])

        attendence = _clinic.PatientAttendOnVisit.create(
            patient=patient,
            dateTimeofvisit=data["dateTimeofvisit"],
            attendtype=data["attendtype"],
            department=data["department"]
            )