使用Python+SqlAlchemy的查询的默认范围
我正在使用Python+SqlAlchemy扩展编写一个应用程序 我有以下代码:使用Python+SqlAlchemy的查询的默认范围,python,flask,sqlalchemy,flask-sqlalchemy,Python,Flask,Sqlalchemy,Flask Sqlalchemy,我正在使用Python+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.Col
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)
是否有办法使对数据库的所有查询自动实现.filterModelName.Is_active==1.limitLIMIT.offsetOFFSET?我不想一直将此块传递给整个应用程序中的所有查询。我想为查询创建一个类似默认范围的内容。许多方法之一是添加类方法。顺便说一句,使用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的可能重复的文档,我不认为这是一个重复的问题。他正试图达到Rails ActiveRecord作用域的相同行为。这正是我要寻找的。非常感谢。只需要一点修正:return Resource.query.filter\u byis\u active=1.limitlimit。offsetoffset@stefanobaldo,已更新。我的打字错误。我很高兴它帮助了你。