manish singh
manish singh

Reputation: 97

Fastapi sqlalchemy pydantic relational field

I am just a starter in FastAPI/Pydantic & SqlAlchemy - I have two model Post and Category where I want Post should fetch Category name instead of only id

when I try to use the below code it gives following error in console

Any help in solving this is much appreciated thank you!

response -> 1 -> category_name
  field required (type=value_error.missing)

post.py models

class Post(Base):
    __tablename__="post"
    id = Column(Integer, primary_key=True, index=True)
    title=Column(String(50))
    user_id=Column(Integer, ForeignKey("users.id"))
    category_id = Column(Integer, ForeignKey("category.id"))
    category_name=relationship("Category", backref="post")


class Category(Base):
    __tablename__="category"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
     

Pydantic models

class CategoryGet(BaseModel):
    id:int
    name:str

    class Config:
        orm_mode=True



class Post(BaseModel):
     
    id = int
    title=str
    user_id=int
    category_id = int
    category_name=CategoryGet 

    class Config:
        orm_mode=True

My mainapp.py

router = APIRouter()


@router.get("/", response_model=List[schemas.VehicleGet])
def get_vehicle(db: Session = Depends(get_db), skip: int = 0, limit: int = 50) -> Any:
    vehicle = crud.post.get_multi(db, skip=skip, limit=limit)
    return vehicle

Upvotes: 0

Views: 1932

Answers (2)

Rivosoa
Rivosoa

Reputation: 61

Pydantic models attributes uses : instead of =

 class Post(BaseModel):
     
    id: int
    title: str
    user_id: int
    category_id: int
    category_name: CategoryGet 

    class Config:
        orm_mode = True

Upvotes: 1

mustafasencer
mustafasencer

Reputation: 753

I guess the problem is that, you forgot orm_mode=True config for you Post model and consequently it is unable to recognize the category_name field. I hope this will solve but if not you could check this thread where an example and some clarification about relationship handling with pydantic.

Upvotes: 0

Related Questions