[英]Response model as list of strings instead of objects
I am trying to return a list of items in FastAPI via a Pydantic model.我正在尝试通过 Pydantic model 返回 FastAPI 中的项目列表。
Currently I have the route:目前我有路线:
from typing import List
from fastapi import Depends
from sqlalchemy.orm.session import Session
...
@router.get('/search-job-types', response_model=List[JobTypeDisplay])
def job_types(search_word: str, db: Session = Depends(get_db)):
return db_dims.search_job_types(search_word, db)
#db_dims:
def search_job_types(search_word: str, db: Session):
s_word = search_word.capitalize()
s_word2 = "%{}%".format(s_word)
all = db.query(DbJobType).filter(DbJobType.name.like(s_word2)).all()
#list_jobs = []
#for item in all:
#list_jobs.append(item.name)
return all
And my schema is as the following:我的模式如下:
from pydantic import BaseModel
class JobTypeDisplay(BaseModel):
name: str
class Config:
orm_mode = True
I am getting a list of objects like this:我得到了这样的对象列表:
[
{
"name": "Something3"
},
{
"name": "Somethin2"
},
{
"name": "Something1"
}
]
But would like something like this:但是想要这样的东西:
['Something3', 'Somethin2', 'Something1']
What is the best way to achieve this and do I really need a loop for it?实现此目标的最佳方法是什么,我真的需要一个循环吗?
If you are only interested in the values of the name
column in your DbJobType
table, then you should 1) change your database query to actually only select that column and 2) utilize the Result.scalars
method to return just a list of strings.如果您只对
DbJobType
表中name
列的值感兴趣,那么您应该1)将数据库查询更改为实际上只有 select 该列,以及2)使用Result.scalars
方法仅返回一个字符串列表。
Here is how that would look:这是它的样子:
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.expression import select
# ... import DbJobType
def search_job_types(search_word: str, db: Session) -> list[str]:
...
statement = select(DbJobType.name).filter() # add your filter options here
result = db.execute(statement)
return result.scalars().all()
Technically, you also don't need to specify a response_model
for the route.从技术上讲,您也不需要为路由指定
response_model
。 If you omit that argument, it will still work.如果您省略该参数,它仍然有效。 Since there is no additional parsing to be done, a proper return type annotation of
list[str]
will be enough to generate the correct OpenAPI schema for that route.由于不需要进行额外的解析,因此
list[str]
的正确返回类型注释足以为该路由生成正确的 OpenAPI 模式。
from fastapi import Depends, FastAPI
from sqlalchemy.orm.session import Session
# ... import search_job_types
app = FastAPI()
...
@app.get("/search-job-types")
def job_types(search_word: str, db: Session = Depends(get_db)) -> list[str]:
return search_job_types(search_word, db)
It seems as though, at least for this route, your JobTypeDisplay
model is obsolete.似乎,至少对于这条路线,您的
JobTypeDisplay
model 已经过时了。
You could change to return_model=list[str]
and change your return statement to您可以更改为
return_model=list[str]
并将返回语句更改为
return [jt.name for jt in all]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.