0

我是 Fast API 的新手,我正在尝试创建一个 api 来返回数据库中的学生。

下面的代码似乎工作

@app.get("/{id}")
async def get_student(id:int):
    return await stud_pydantic.from_queryset_single(Student.get(id=id))

这似乎也有效

@app.get("/{id}")
async def get_student(id:int):
    stud_obj = Student.get(id=id)
    return await stud_pydantic.from_tortoise_orm(stud_obj)

但是,这不起作用

@app.get("/{id}")
async def get_student(id:int):
    stud_obj = Student.get(id=id)
    return await stud_pydantic.from_queryset_single(stud_obj)

但是,两者基本上都试图返回一个学生对象。正确的 ?那么,有什么区别。好像我不明白 from_queryset_single 和 from_tortoise_orm 方法之间的区别

这是我的学生模型

class Student(models.Model):
    name = fields.CharField(50,unique=True)
    age = fields.IntField()
    id = fields.IntField(pk=True)

stud_pydantic = pydantic_model_creator(Student,name="student")
studRO_pydantic = pydantic_model_creator(Student,name="studentRO",exclude_readonly=True)

提前致谢

4

1 回答 1

0

我认为您需要等待从数据库中获取数据的过程。

@app.get("/{id}")
async def get_student(id:int):
    stud_obj = await Student.get(id=id)
    return await stud_pydantic.from_queryset_single(stud_obj)
于 2021-05-31T11:45:20.530 回答