一尘不染

pydantic.error_wrappers.ValidationError:值不是有效列表(type=type_error.list)

py

FastAPI 新手


获取“值不是有效列表(type=type_error.list)”错误

每当我尝试返回 {“posts”: post}

@router.get('', response_model = List[schemas.PostResponseSchema])
def get_posts(db : Session = Depends(get_db)):
 print(limit)
 posts = db.query(models.Post).all()
 return {"posts" : posts}

虽然如果我返回这样的帖子它会起作用:

return posts

这是我的响应模型:

class PostResponseSchema(PostBase):
 user_id: int
 id: str
 created_at : datetime
 user : UserResponseSchema

 class Config:
     orm_mode = True

和型号:

class Post(Base):
 __tablename__ = "posts"
 id =  Column(Integer, primary_key=True, nullable=False)
 title = Column(String, nullable=False)
 content = Column(String, nullable = False)
 published = Column(Boolean, server_default = 'TRUE' , nullable = False)
 created_at = Column(TIMESTAMP(timezone=True), nullable = False, server_default = 
  text('now()'))
 user_id = Column(Integer, ForeignKey("users.id", ondelete = "CASCADE"), nullable = 
  False )

 user = relationship("User")

我在这里想念什么?


阅读 80

收藏
2022-10-08

共1个答案

一尘不染

您的回复预计是您的这行代码的列表:

@router.get('', response_model = List[schemas.PostResponseSchema])

但你的回应return {"posts" : posts} 是反对。

因此您必须返回帖子,因为它是您的响应所期望的对象列表。否则,如果你想使用return {"posts": posts}just change router.get('', response_model = List[schemas.PostResponseSchema])torouter.get('')那么你会得到这样的东西:

{"posts": [......]}

[] 内将是一个帖子列表。

2022-10-08