fastapi-pagination icon indicating copy to clipboard operation
fastapi-pagination copied to clipboard

paginate expecting a different type than it gets for its items

Open YarrikV opened this issue 1 year ago • 1 comments

The project I am working on has schemas used in the api and models which are stored in the database (using SQLAlchemy as interface).

The schemas and models are different because of reasons which are irrelevant to this issue.

Current behavior

I am implementing pagination, but the issue is that paginate() is expecting its items to be of the schema-type, and it knows this from the endpoint details, while I first fetch them as models on paginate.

I can go around this by transforming the items to the schema's. However, this is not ideal since I want to do some things inbetween those two actions (fetching items with paginate and transforming the items into the schema's).

Expected behavior

I would love to be able to specify somewhere which pydantic model the paginate function will expect.

YarrikV avatar Apr 29 '24 08:04 YarrikV

Hi @YarrikV,

I guess you can try to use set_page function, it can be used with with statement to set page class for a specific context.

Here is an example:

@app.get('/users')
def get_users(db: Session = Depends(get_db)) -> Page[UserOut]:
    with set_page(Page[User]):
        page = paginate(db, select(User).order_by(User.created_at))

    # here you can do something with page, items will pe of User type

    return page

uriyyo avatar Apr 29 '24 20:04 uriyyo

Hi @YarrikV,

Any updates?

uriyyo avatar Jun 08 '24 08:06 uriyyo

I had solved this issue by avoiding it as a temporary solution. However, I will have another look at it this week, and will get back to you and close the issue if this fixed it for me.

YarrikV avatar Jun 10 '24 15:06 YarrikV

Hi @YarrikV,

I guess you can try to use set_page function, it can be used with with statement to set page class for a specific context.

Here is an example:

@app.get('/users')
def get_users(db: Session = Depends(get_db)) -> Page[UserOut]:
    with set_page(Page[User]):
        page = paginate(db, select(User).order_by(User.created_at))

    # here you can do something with page, items will pe of User type

    return page

This solved my problem and provides a more flexible alternative to using the transformer function. Thanks!

YarrikV avatar Jun 17 '24 08:06 YarrikV