paginate expecting a different type than it gets for its items
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.
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
Hi @YarrikV,
Any updates?
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.
Hi @YarrikV,
I guess you can try to use
set_pagefunction, it can be used withwithstatement 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!