Last active
August 29, 2015 14:10
-
-
Save pawl/ddf91137d416137f7798 to your computer and use it in GitHub Desktop.
Single Custom Filter Requiring Joins
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import os.path as op | |
| from flask import Flask | |
| from flask.ext.sqlalchemy import SQLAlchemy | |
| from flask.ext import admin | |
| from flask.ext.admin.contrib import sqla | |
| from flask.ext.admin.contrib.sqla import filters | |
| # Create application | |
| app = Flask(__name__) | |
| # Create dummy secrey key so we can use sessions | |
| app.config['SECRET_KEY'] = '123456790' | |
| # Create in-memory database | |
| app.config['DATABASE_FILE'] = 'sample_db.sqlite' | |
| app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE'] | |
| app.config['SQLALCHEMY_ECHO'] = True | |
| db = SQLAlchemy(app) | |
| class Model1(db.Model): | |
| def __init__(self, test1=None): | |
| self.test1 = test1 | |
| id = db.Column(db.Integer, primary_key=True) | |
| test1 = db.Column(db.String(20)) | |
| def __unicode__(self): | |
| return self.test1 | |
| def __str__(self): | |
| return self.test1 | |
| class Model2(db.Model): | |
| def __init__(self, string_field=None): | |
| self.string_field = string_field | |
| id = db.Column(db.Integer, primary_key=True) | |
| string_field = db.Column(db.String) | |
| # Relation | |
| model1_id = db.Column(db.Integer, db.ForeignKey(Model1.id)) | |
| model1 = db.relationship(Model1, backref='model2') | |
| # Flask views | |
| @app.route('/') | |
| def index(): | |
| return '<a href="/admin/">Click me to get to Admin!</a>' | |
| # Customized User model admin | |
| class Model2View(sqla.ModelView): | |
| column_filters = [ | |
| #'model1.test1' #uncomment to fix | |
| filters.FilterEqual(Model1.test1, "Test1"), | |
| ] | |
| # Create admin | |
| admin = admin.Admin(app, name='Example: SQLAlchemy') | |
| # Add views | |
| admin.add_view(Model2View(Model2, db.session)) | |
| def build_sample_db(): | |
| db.drop_all() | |
| db.create_all() | |
| # Create parent/child values | |
| for count in range(1, 5): | |
| model2_obj = Model2("model2_val" + str(count)) | |
| model2_obj.model1 = Model1("model1_val" + str(count)) | |
| db.session.add(model2_obj) | |
| db.session.commit() | |
| if __name__ == '__main__': | |
| # Build a sample db on the fly, if one does not exist yet. | |
| app_dir = op.realpath(os.path.dirname(__file__)) | |
| database_path = op.join(app_dir, app.config['DATABASE_FILE']) | |
| if not os.path.exists(database_path): | |
| build_sample_db() | |
| # Start app | |
| app.run(debug=True, host="0.0.0.0", port=5090) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment