Default scope for queries using Python + Flask-SqlAlchemy -


i writing application using python + flask-sqlalchemy extension.

i have following code:

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()     row in data:         resources.append(             resources_show(row)         )     return envelope(resources) 

is there way make queries database automatically implement .filter(modelname.is_active == 1).limit(limit).offset(offset)? not want keep passing block queries in whole application. want create default scope queries.

one of many ways add class method. python class definition, free add own methods, way.

class resource(db.model):     # .... existing code     @staticmethod     def customq(limit, offset):         """this method returns instance of flask_sqlalchemy.basequery"""         return resource.query.filter_by(is_active=1).limit(limit).offset(offset) 

then example code becomes:

@app.route('/resources', methods=['get']) def resources_get_all():     get_limits()     resources = []     data = resource.customq(limit, offset).all() 

here documentation on flask_sqlalchemy's basequery


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -