python 为什么我必须迭代SQLAlchemy对象才能在FastAPI中返回它?

rqqzpn5f  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(120)

GET端点不工作:

@app.get("/question/", response_model=list[schemas.QuizSchema])
def get_questions(db: Session = Depends(get_db)):
    quiz = db.query(models.Quiz).all()
    return jsonable_encoder(quiz)

它会引发以下错误:

raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 3 validation errors for QuizSchema
response -> 0 -> category
  field required (type=value_error.missing)
response -> 0 -> answer
  field required (type=value_error.missing)
response -> 0 -> question
  field required (type=value_error.missing)

但这段代码运行得很好:

@app.get("/question/", response_model=list[schemas.QuizSchema])
def get_questions(db: Session = Depends(get_db)):
    quiz = db.query(models.Quiz).all()
    for x in quiz:
        print(x.id, x.category.id, x.answer[0].id, x.question.id)
    return jsonable_encoder(quiz)

我真的不明白这是怎么回事。
我在for-循环前后使用了一个断点,如下所示:

@app.get("/question/", response_model=list[schemas.QuizSchema])
def get_questions(db: Session = Depends(get_db)):
    quiz = db.query(models.Quiz).all()
    breakpoint()
    for x in quiz:
        print(x.id, x.category.id, x.answer[0].id, x.question.id)
    breakpoint()
    return jsonable_encoder(quiz)

这就是结果:

# FIRST BREAKPOINT
(Pdb) quiz
[<models.Quiz object at 0x7fb81957c5e0>]
(Pdb) jsonable_encoder(quiz)
[{'id': 2}]
(Pdb) continue
2 3 1 1
> /backend/main.py(29)get_questions()
-> return jsonable_encoder(quiz)

#SECOND BREAKPOINT
(Pdb) quiz
[<models.Quiz object at 0x7fb81957c5e0>]
(Pdb) jsonable_encoder(quiz)
[{'id': 2, 'category': {'quiz_category_id': 2, 'id': 3, 'name': 'foo'}, 'answer': [{'name': 'zdecydowanie nie', 'value': -2, 'id': 1}, {'name': 'raczej nie', 'value': -1, 'id': 2}, {'name': 'nie wiem', 'value': 0, 'id': 3}, {'name': 'raczej tak', 'value': 1, 'id': 4}, {'name': 'zdecydowanie tak', 'value': 2, 'id': 5}], 'question': {'name': 'bar', 'quiz_question_id': 2, 'id': 1}}]
(Pdb)

我的SQLAlchemy模型看起来像这样:

class Quiz(Base):
    __tablename__ = "quiz"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    category: Mapped["Category"] = relationship(back_populates="quiz_category")
    answer: Mapped[list[Answer]] = relationship(secondary=quiz_answer)
    question: Mapped["Question"] = relationship(back_populates="quiz_question")
0sgqnhkj

0sgqnhkj1#

架构应该有配置类,其中应该有orm_mode = True

class QuizSchema(BaseModel):
  .... field 
  class Config(): 
     orm_mode = True

相关问题