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

Cursor pagination, sqlalchemy and lazy joined

Open Nnonexistent opened this issue 1 year ago • 2 comments

When using lazy="joined" in sqlalchemy model relationship with cursor pagination, the pagination will fail with the message:

The unique() method must be invoked on this Result, as it contains results that include joined eager loads against collections

Example (slightly modified test case initial condition):

class User(sa_base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)

    orders = relationship("Order", back_populates="user", lazy="joined")  # <- here, instead of "noload"

The case is probably due to unique option from paginate is not propagated down to the sqlakeyset's implementation of the cursor pagination. So no _maybe_unique function is invoked leading to this error.

Maybe there is a way of workaround this issue without dropping use of lazy loading?

Nnonexistent avatar Apr 10 '24 14:04 Nnonexistent

Hi @Nnonexistent,

It's a kinda tricky thing, I guess we need to open issue in sqlakeyset.

As a workaround you can try to change joinedload to selectinload, it will not require you to call unique.

uriyyo avatar Apr 15 '24 09:04 uriyyo