Reputation: 647
New to fast API, not able to find where I am doing wrong
Here is my router -
@router.get('/{user_id}/salesbill', response_model=list[schemas.ShowSalesBill], status_code=status.HTTP_200_OK)
def get_all_salesbills(user_id: int, db: Session = Depends(get_db)):
objs = db.query(bill_model.SalesBillModel).filter(bill_model.SalesBillModel.user_id==user_id)
print(objs, "=================")
return objs
Here is my schemas --
class BillBase(BaseModel):
bill_no: int
amount: int
about: str
class ShowSalesBill(BillBase):
id: int
class Config:
orm_mode = True
Here is my model -
class SalesBillModel(Base):
__tablename__ = "salesbill"
id = Column(Integer, primary_key=True, index=True)
bill_no = Column(Integer, index=True)
amount = Column(Integer, nullable=False)
about = Column(String(50), nullable=True)
user_id = Column(Integer, ForeignKey("users.id", ondelete='CASCADE'))
user = relationship("User", back_populates="salesbills")
So, I am trying to get all the bills added by the user but getting an error
pydantic.error_wrappers.ValidationError: 1 validation error for ShowSalesBill response value is not a valid list (type=type_error.list)
Getting this error
SELECT salesbill.id AS salesbill_id, salesbill.bill_no AS salesbill_bill_no, salesbill.amount AS salesbill_amount, salesbill.about AS salesbill_about, salesbill.user_id AS salesbill_user_id
FROM salesbill
WHERE salesbill.user_id = ? =================
INFO: 127.0.0.1:47410 - "GET /1/salesbill HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/mdhv/fastapi/env/lib/python3.10/site-packages/uvicorn/protocols/http/httptools_impl.py", line 419, in run_asgi
result = await app( # type: ignore[func-returns-value]
Upvotes: 0
Views: 95
Reputation: 148
to understand the error : the response model you are putting in requires a List
of schemas.ShowSalesBill and you are not returning the same as expected.
I suggest you add id to the BillBase
class BillBase(BaseModel):
id : int
bill_no: int
amount: int
about: str
then you create a pedantic model that have a column with a list of BillBase:
class ShowSalesBill(BaseModel):
bill_list: Optional[list[BillBase]] = []
class Config:
orm_mode = True
then your endpoint became like this
@router.get('/{user_id}/salesbill', response_model=schemas.ShowSalesBill, status_code=status.HTTP_200_OK)
def get_all_salesbills(user_id: int, db: Session = Depends(get_db)):
objs = db.query(bill_model.SalesBillModel).filter(bill_model.SalesBillModel.user_id==user_id).all()
return schemas.ShowSalesBill(
bill_list=[schemas.BillBase(**bill.__dict__) for bill in objs]
)
I hope it helps!
Upvotes: 1