简体   繁体   English

有没有办法在前端的sqlmodel中对相关数据进行分页

[英]Is there a way to paginate related data in sqlmodel on the frontend

The sqlmodel docs gives an example of two classes sqlmodel 文档给出了两个类的示例

class Team(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)
    headquarters: str

    heroes: List["Hero"] = Relationship(back_populates="team")


class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)
    secret_name: str
    age: Optional[int] = Field(default=None, index=True)

    team_id: Optional[int] = Field(default=None, foreign_key="team.id")
    team: Optional[Team] = Relationship(back_populates="heroes")

I could get a Team object using the following code example我可以使用以下代码示例获得团队 object

def get_team():
    with Session(engine) as session:
        statement = select(Team).where(Team.name == "avengers")
        result = session.exec(statement)
        avengers = result.one()
        return avengers

and doing avengers.heroes should return a list of all heroes related to that object but What if the list contains thousands of items?并执行avengers.heroes应该返回与 object 相关的所有英雄的列表,但是如果列表包含数千个项目怎么办? is there a way to paginate this without having to make a separate query to the heroes table by myself?有没有一种方法可以对此进行分页,而不必自己单独查询 heroes 表?

To do this, you have to work with the underlying SQLAlchemy library, which you can do using the sa_relationship_kwargs argument to Relationship .为此,您必须使用底层 SQLAlchemy 库,您可以使用Relationshipsa_relationship_kwargs参数来实现。

As mentioned in this answer , if you specify the relationship as dynamic, you can then paginate it.正如这个答案中提到的,如果您将关系指定为动态关系,则可以对其进行分页。 Using SQLModel, it looks something like this:使用 SQLModel,它看起来像这样:

class Team(SQLModel, table=True):
    ...
    heroes: List["Hero"] = Relationship(
        back_populates="team",
        sa_relationship_kwargs={"order_by": "Hero.name", "lazy": "dynamic"},
    )

# When calling it
first_ten_heroes = team.heroes[:10]  # or team.heroes.limit(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM