代码之家  ›  专栏  ›  技术社区  ›  TenSzalik

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

  •  0
  • TenSzalik  · 技术社区  · 3 年前

    这个 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")
    
    0 回复  |  直到 3 年前
        1
  •  0
  •   Brian Tompsett - 汤莱恩 andrewwong97    3 年前

    架构应在其应有的位置具有配置类 orm_mode = True :

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