簡體   English   中英

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

[英]pydantic.error_wrappers.ValidationError : value is not a valid list (type=type_error.list)

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

這是我的回復 model:

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

 class Config:
     orm_mode = True

和 Model:

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")

我在這里錯過了什么?

您的回復應該是您的這行代碼的列表:

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

但您的回復return {"posts": posts}是 object。

所以你必須返回帖子,因為它是你的響應所期望的對象列表。 否則,如果你想使用return {"posts": posts}只需將router.get('', response_model = List[schemas.PostResponseSchema])更改為router.get('')然后你會得到這樣的東西:

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

[] 內將是一個帖子列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM