FastAPI pydantic.error_wrappers.ValidationError

Viewed 4431

I am using the below model and schema in FastAPI.

Models

class Item(Base):
    __tablename__ = "items"

    id = Column(Integer, primary_key=True,index=True)
    name = Column(String(80), nullable=False, unique=True,index=True)
    price = Column(Float(precision=2), nullable=False)
    description = Column(String(200))
    store_id =Column(Integer,ForeignKey('stores.id'),nullable=False)
    def __repr__(self):
        return 'ItemModel(name=%s, price=%s,store_id=%s)' % (self.name, self.price,self.store_id)
    
class Store(Base):
    __tablename__ = "stores"
    id = Column(Integer, primary_key=True,index=True)
    name = Column(String(80), nullable=False, unique=True)
    items = relationship("Item",lazy="dynamic",primaryjoin="Store.id == Item.store_id")

    def __repr__(self):
        return 'Store(name=%s)' % self.name

Schemas

class ItemBase(BaseModel):
    name: str
    price : float
    description: Optional[str] = None
    store_id: int


class ItemCreate(ItemBase):
    pass


class Item(ItemBase):
    id: int

    class Config:
        orm_mode = True


class StoreBase(BaseModel):
    name: str

class StoreCreate(StoreBase):
    pass

class Store(StoreBase):
    id: int
    items: List[Item] = []

    class Config:
        orm_mode = True

I have created a Store Object in the database. When I am trying to fetch all the stores stored in the database using the below API.

@app.get('/stores', tags=["Store"],response_model=List[schemas.Store])
def get_all_stores(name: Optional[str] = None,db: Session = Depends(get_db)):
    """
    Get all the Stores stored in database
    """
    if name:
        stores =[]
        db_store = StoreRepo.fetch_by_name(db,name)
        print(db_store)
        stores.append(db_store)
        return stores
    else:
        return StoreRepo.fetch_all(db)

[packages]
fastapi = "==0.68.1"
uvicorn = "==0.15.0"
sqlalchemy = "==1.4.23"

I am getting the below exception

raise ValidationError(errors, field.type_)

pydantic.error_wrappers.ValidationError: 1 validation error for Store response -> 0 -> items value is not a valid list (type=type_error.list)

If we remove the response_model=List[schemas.Store] from the API then it works fine.

Any help will be appreciated.

1 Answers

I am able to resolve the above issue after updating the relationship in Store Model.

items = relationship("Item",primaryjoin="Store.id == Item.store_id",cascade="all, delete-orphan")

Sharing it in case it helps someone.

Related