python - 使用 Python + Flask-SqlAlchemy 的默认查询范围

标签 python flask sqlalchemy flask-sqlalchemy

我正在使用 Python + Flask-SqlAlchemy 扩展编写一个应用程序。

我有以下代码:

class Resource(db.Model):
    __tablename__ = 'resources'
    id = db.Column(db.Integer, primary_key=True)
    created_at = db.Column(db.DateTime)
    updated_at = db.Column(db.DateTime)
    is_active = db.Column(db.Boolean)
    key = db.Column(db.String(64))
    title = db.Column(db.String(64))

    def __init__(self):
        self.created_at = datetime.now()
        self.updated_at = datetime.now()
        self.is_active = 1

@app.route('/resources', methods=['GET'])
def resources_get_all():
    get_limits()
    resources = []
    data = Resource.query.filter(Resource.is_active == 1).limit(LIMIT).offset(OFFSET).all()
    for row in data:
        resources.append(
            resources_show(row)
        )
    return envelope(resources)

有没有办法让所有对数据库的查询自动实现.filter(ModelName.is_active == 1).limit(LIMIT).offset(OFFSET)?我不想继续将此 block 传递给整个应用程序中的所有查询。我想创建类似于查询的默认范围之类的内容。

最佳答案

多种方法之一是添加类方法。顺便说一句,通过 python 类定义,您可以自由添加自己的方法。

class Resource(db.Model):
    # .... your existing code
    @staticmethod
    def customq(limit, offset):
        """This method returns an instance of flask_sqlalchemy.BaseQuery"""
        return Resource.query.filter_by(is_active=1).limit(limit).offset(offset)

然后你的示例代码变成:

@app.route('/resources', methods=['GET'])
def resources_get_all():
    get_limits()
    resources = []
    data = Resource.customq(LIMIT, OFFSET).all()

这是关于flask_sqlalchemy的BaseQuery的文档

关于python - 使用 Python + Flask-SqlAlchemy 的默认查询范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27505755/

相关文章:

python - 将行附加到excel表python的顶部

python - 打开 urllib2 握手失败的页面

python - Flask 中的多个提交按钮

python - 将 Python Flask 应用程序拆分为多个文件

python - 无法比较原始偏移和偏移感知日期时间 - last_seen 选项

python - 使用 Flask-SQLAlchemy 反射(reflect)表引发 RuntimeError : application not registered

Python time.gmtime() 返回比系统时间提前 5 小时的时间

python - SqlAlchemy alembic 迁移文件不使用 env.py 中的连接设置?

python - sqlalchemy 中是否有一种解决方法可以在没有任何主键的情况下从数据库加载表?

python - 从 PLY 向解析器的调用者报告解析错误