[英]Error in a response_model validation in FastAPI
我在 fastapi 中的 response_model 有一個錯誤
我,我正在學習 FastApi 並且我有這個模式:
class BasicArticle(BaseModel):
title: str
content: str
published: bool
class ArticleBase(BasicArticle):
creator_id: int
class UserInArticle(BaseModel):
id: int
username: str
class Config:
orm_mode: True
class ArticleDisplay(BasicArticle):
user: UserInArticle
class Config:
orm_mode = True
這些是我的模型:
class DbUser(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String)
email = Column(String)
password = Column(String)
items = relationship("DbArticle", back_populates="user")
class DbArticle(Base):
__tablename__ = "articles"
id = Column(Integer, primary_key=True, index=True)
title = Column(String)
content = Column(String)
published = Column(Boolean)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship("DbUser", back_populates="items")
我在這里創建帖子:
def create_article(db: Session, request: ArticleBase):
new_article = DbArticle(
title=request.title,
content=request.content,
published=request.published,
user_id=request.creator_id
)
db.add(new_article)
db.commit()
db.refresh(new_article)
return new_article
最后,這是終點:
@router.post('/', response_model=ArticleDisplay, status_code=status.HTTP_201_CREATED)
def create_article(request: ArticleBase, db: Session = Depends(get_db)):
return db_article.create_article(db, request)
問題是:
pydantic.error_wrappers.ValidationError: 1 validation error for ArticleDisplay
response -> user
value is not a valid dict (type=type_error.dict)
類配置:orm_mode = True
應該為此工作,至少在我正在學習的課程中是這樣,但我不知道自課程創建以來 pydantic 是否發生了變化。
我感謝每一個答案
無法生成錯誤,但建議根據您的 python 版本遵循以下簡單的 crud。
https://github.com/tiangolo/fastapi/tree/master/docs_src/sql_databases/sql_app
參考: https ://fastapi.tiangolo.com/tutorial/sql-databases/#__tabbed_4_2
您的UserInArticle模型中似乎有錯字:
class UserInArticle(BaseModel):
id: int
username: str
class Config:
orm_mode: True # Should be "= True" and not ": True"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.