Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does db.query(Item).all().filter(Item.is_active == True) fail with error AttributeError: 'list' object has no attribute 'filter'

As the title says, adding a .filter after the db.query(Item).all() fails with AttributeError: ‘list’ object has no attribute ‘filter’.

    items = db.query(Item).all().filter(Item.is_active == True)
    return items

But if i remove the .filter it works but i really want to filter.

def list_items(db : Session):
    items = db.query(Item).all()
    return items

Here is the route:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@router.get("/all", response_model=List[ShowItem])
def read_items(db: Session = Depends(get_db)):
    items = list_items(db=db)
    return items

Here is the class:

class Item(BaseModel):
    name: str
    price: int

    class Config():
        orm_mode = True

Here is the Table DB Model:

class Item(Base):
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, nullable=False)
    price = (Column(Integer, nullable=False))
    is_active = Column(Boolean(), default=True)

>Solution :

.all() method returns list which does not have filter method, you need to 1st use filter then all that is replace

items = db.query(Item).all().filter(Item.is_active == True)

using

items = db.query(Item).filter(Item.is_active == True).all()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading