【问题标题】:How to return a list field in FastAPI?如何在 FastAPI 中返回列表字段?
【发布时间】:2020-05-22 11:37:03
【问题描述】:

我使用的模型如下:

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

这是已经存储在数据库中的数据:

但它无法正确返回 list 字段 (answer_false),并且该字段的值作为字符返回:

我做错了什么,我应该如何解决这个问题?

【问题讨论】:

    标签: python-3.x fastapi pydantic


    【解决方案1】:

    这是因为我的 sqlalchemy 配置。我在表的配置中删除了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")),
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 2021-03-25
      相关资源
      最近更新 更多