如何 return FastAPI 中的列表字段?
How to return a list field in FastAPI?
我使用的模型如下:
class Question(BaseModel):
id: int
title: str = Field(..., min_length=3, max_length=50)
answer_true: str = Field(..., min_length=3, max_length=50)
answer_false: list
category_id: int
并尝试使用以下函数获取 questions
:
def get(id: int):
query = questions.select().where(id == questions.c.id)
return database.fetch_one(query=query)
@router.get("/{id}/", response_model=Question)
def read_question(id: int = Path(..., gt=0),):
question = get(id)
if not question:
raise HTTPException(status_code=404, detail="question not found")
return question
这是已存储在数据库中的数据:
但它不能 return list
字段 (answer_false
) 正确并且该字段的值被 return 编辑为字符:
我做错了什么,我应该如何解决这个问题?
这是因为我的 sqlalchemy 配置。我在 table 的配置中删除了 dimensions
,问题得到解决:
questions = Table(
"questions",
metadata,
Column("id", Integer, primary_key=True),
Column("title", String(50)),
Column("answer_true", String(50)),
Column("answer_false", ARRAY(String)), ## adding dimension will cause the list to not work in get requests
Column("created_date", DateTime, default=func.now(), nullable=False),
Column("category_id", Integer, ForeignKey("categories.id")),
)
我使用的模型如下:
class Question(BaseModel):
id: int
title: str = Field(..., min_length=3, max_length=50)
answer_true: str = Field(..., min_length=3, max_length=50)
answer_false: list
category_id: int
并尝试使用以下函数获取 questions
:
def get(id: int):
query = questions.select().where(id == questions.c.id)
return database.fetch_one(query=query)
@router.get("/{id}/", response_model=Question)
def read_question(id: int = Path(..., gt=0),):
question = get(id)
if not question:
raise HTTPException(status_code=404, detail="question not found")
return question
这是已存储在数据库中的数据:
但它不能 return list
字段 (answer_false
) 正确并且该字段的值被 return 编辑为字符:
我做错了什么,我应该如何解决这个问题?
这是因为我的 sqlalchemy 配置。我在 table 的配置中删除了 dimensions
,问题得到解决:
questions = Table(
"questions",
metadata,
Column("id", Integer, primary_key=True),
Column("title", String(50)),
Column("answer_true", String(50)),
Column("answer_false", ARRAY(String)), ## adding dimension will cause the list to not work in get requests
Column("created_date", DateTime, default=func.now(), nullable=False),
Column("category_id", Integer, ForeignKey("categories.id")),
)