uriyyo / fastapi-pagination

FastAPI pagination πŸ“–
https://uriyyo-fastapi-pagination.netlify.app/
MIT License
1.19k stars 136 forks source link

Can't get SqlAlchemy example to work #283

Closed leechenghan closed 2 years ago

leechenghan commented 2 years ago

I'm following the SqlAlchemy tutorial but keep getting this error

TypeError: object of type 'Query' has no len()

Here's my code

@router.get("/", response_model=Page[schemas.Transaction])
async def get_transactions(
    start: datetime,
    end: datetime,
    params: Params = Depends(),
    db: Session = Depends(get_db),
):
    return paginate(
        db.query(Transaction).filter(
            Transaction.timestamp >= start, Transaction.timestamp <= end
        ),
        params,
    )

When I add an .all() to the end of my query object, it works.

Also, does this library actually help create the pagination query in the SqlAlchemy query builder? Or is it simply paginating whatever results the query returns?

e.g. does it actually add .limit() and .offset() to the queries? Looking through the code, it doesn't seem like it.

uriyyo commented 2 years ago

You should use pagination from fastapi_pagination.ext.sqlalchemy:

from fastapi_pagination.ext.sqlalchemy import paginate

@router.get("/", response_model=Page[schemas.Transaction])
async def get_transactions(
    start: datetime,
    end: datetime,
    params: Params = Depends(),
    db: Session = Depends(get_db),
):
    return paginate(
        db.query(Transaction).filter(
            Transaction.timestamp >= start, Transaction.timestamp <= end
        ),
        params,
    )

Working example - https://github.com/uriyyo/fastapi-pagination/blob/main/examples/pagination_sqlalchemy.py

P.S. Russia invaded my country Ukraine, I am not able to respond and it can be my last reply😟

opyate commented 2 years ago

P.S. Russia invaded my country Ukraine, I am not able to respond and it can be my last reply

πŸ‡ΊπŸ‡¦ + πŸ‡ͺπŸ‡Ί We stand with you, my friend πŸ‘πŸ»

leechenghan commented 2 years ago

You should use pagination from fastapi_pagination.ext.sqlalchemy:

from fastapi_pagination.ext.sqlalchemy import paginate

@router.get("/", response_model=Page[schemas.Transaction])
async def get_transactions(
    start: datetime,
    end: datetime,
    params: Params = Depends(),
    db: Session = Depends(get_db),
):
    return paginate(
        db.query(Transaction).filter(
            Transaction.timestamp >= start, Transaction.timestamp <= end
        ),
        params,
    )

Working example - https://github.com/uriyyo/fastapi-pagination/blob/main/examples/pagination_sqlalchemy.py

P.S. Russia invaded my country Ukraine, I am not able to respond and it can be my last reply😟

I hope peace returns to the region soon πŸ™

uriyyo commented 2 years ago

@leechenghan I am closing this issue. Please, reopen it in case of any issues.