简体   繁体   中英

Error in a response_model validation in FastAPI

I have an error from a response_model in fastapi

I, I'm learning FastApi and I have this schemas:

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

These are my models:

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

Here I create the post:

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

And finally, this is the endpoint:

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

The problem is:

pydantic.error_wrappers.ValidationError: 1 validation error for ArticleDisplay
response -> user
  value is not a valid dict (type=type_error.dict)

The class Config: orm_mode = True

should be working for this, at least it does in the course I'm following, but I don't know if pydantic have changed since the moment when the course were created.

I appreciate every answer

Unable to generate the error, but would suggest to follow the below simple crud based on your python version.

https://github.com/tiangolo/fastapi/tree/master/docs_src/sql_databases/sql_app

Reference: https://fastapi.tiangolo.com/tutorial/sql-databases/#__tabbed_4_2

It seems like you have a typo in your UserInArticle model:

class UserInArticle(BaseModel):
    id: int
    username: str

    class Config:
        orm_mode: True  # Should be "= True" and not ": True"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM