我正在尝试将患者批量添加到数据库中,但遇到了一个错误。 目标是从请求体读取数据,截断表中的数据并添加新数据。 有人能告诉我我做错了什么吗
代码
schemas.py
from pydantic import BaseModel
from typing import Optional
class PatientBase(BaseModel):
ticket_id: str
patient_name: Optional[str] = None
class PatientInDb(PatientBase):
patient_id : str
institute :str
class Config:
orm_mode = True
crud.py
from typing import List
from sqlalchemy.orm import Session
def create_patients(db: Session, patients: List[schemas.PatientInDb] ):
num_of_deleted_rows = db.query(models.Patient).delete()
db.add_all(patients)
db.commit()
return db.query(models.Patient).count()
patients.py
@router.post("/patients")
async def post_patients(
patients : List[schemas.PatientInDb],
db: Session = Depends(get_db),
):
patients_count = crud.create_patients(db, patients)
return {
"message":f"New {patients_count} patients created."
}
错误
File ".\app\api\v1\patients.py", line 45, in post_patients
patients_count = crud.create_patients(db, patients)
File ".\app\crud.py", line 13, in create_patients
db.add_all(patients)
File "c:\users\convergytics\miniconda3\envs\test\lib\site-packages\sqlalchemy\orm\session.py", line 2016, in add_all
for instance in instances:
File "c:\users\convergytics\miniconda3\envs\test\lib\typing.py", line 682, in inner
return func(*args, **kwds)
File "c:\users\convergytics\miniconda3\envs\test\lib\typing.py", line 1107, in __getitem__
params = tuple(_type_check(p, msg) for p in params)
File "c:\users\convergytics\miniconda3\envs\test\lib\typing.py", line 1107, in <genexpr>
params = tuple(_type_check(p, msg) for p in params)
File "c:\users\convergytics\miniconda3\envs\test\lib\typing.py", line 374, in _type_check
raise TypeError(msg + " Got %.100r." % (arg,))
TypeError: Parameters to generic types must be types. Got 0.
在文件“patients.py”中
更改:
到
原因“=”用于指定默认值,“:”用于引用类型
您在discord上也得到了这个答案,但是您正在保存pydantic模型,而不是sqlalchemy模型
相关问题 更多 >
编程相关推荐