sqlachemy 一对多关系查找,如何实现分页

class DictKey(BaseModel):
    """
    字典键
    """
    __tablename__ = 'dict_key'

    id = db.Column(db.BigInteger, primary_key=True)
    source = db.Column(db.Integer, nullable=False)
    key = db.Column(db.String(20), nullable=False)
    name = db.Column(db.String(20), nullable=False)
    remark = db.Column(db.String(50), nullable=False)
    values = db.relationship('DictValue', foreign_keys='DictValue.key_name', backref='key')

class DictValue(BaseModel):
    """
    字典值
    """
    __tablename__ = 'dict_value'

    id = db.Column(db.BigInteger, primary_key=True)
    value = db.Column(db.String(100), nullable=False)
    name = db.Column(db.String(20), nullable=False)
    sort = db.Column(db.Integer, nullable=False))
    dict_key = db.Column('dict_key_id', db.BigInteger, db.ForeignKey('dict_key.id'), nullable=True, doc='字典key id')
    key_name = db.Column(db.String(20), db.ForeignKey('dict_key.key'), index=True, doc='字典key key')

连表查询语句:

query = DictKey.query.join(DictKey.values).options(contains_eager(DictKey.values)).offset(pagesize * (page - 1)).limit(pagesize).all()

此时的分页是根据字典值的个数进行分页,不符合期望。希望根据字典key的个数进行分页。

对手动分页不是很熟悉,不过你可以参考 Flask-SQLAlchemy 的分页实现:

https://github.com/pallets/flask-sqlalchemy/blob/main/src/flask_sqlalchemy/__init__.py#L342