Skip to content

Instantly share code, notes, and snippets.

@pawl
Last active March 12, 2018 00:03
Show Gist options
  • Save pawl/6589cebdcacf9afe7e50 to your computer and use it in GitHub Desktop.
Save pawl/6589cebdcacf9afe7e50 to your computer and use it in GitHub Desktop.
Hybrid Properties In Flask Admin - Error
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.hybrid import hybrid_property
import flask_admin as admin
from flask_admin.contrib import sqla
from flask_admin.contrib.sqla.filters import BaseSQLAFilter, FilterEqual
# 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['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample_db_2.sqlite'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
# Flask views
@app.route('/')
def index():
return '<a href="/admin/">Click me to get to Admin!</a>'
class Screen(db.Model):
__tablename__ = 'screen'
id = db.Column(db.Integer, primary_key=True)
width = db.Column(db.Integer, nullable=False)
height = db.Column(db.Integer, nullable=False)
@hybrid_property
def number_of_pixels(self):
return self.width * self.height
@number_of_pixels.expression
def number_of_pixels(cls):
return db.select([cls.width * cls.height]).as_scalar()
class ScreenAdmin(sqla.ModelView):
can_edit = False
column_display_pk = True
list_columns = ['id', 'width', 'height', 'number_of_pixels']
column_filters = [FilterEqual(Screen.number_of_pixels, 'Number of Pixels')]
def get_query(self):
return super(ScreenAdmin, self).get_query().filter(Screen.number_of_pixels >= 100)
# Create admin
admin = admin.Admin(app, name='Example: SQLAlchemy2', template_mode='bootstrap3')
admin.add_view(ScreenAdmin(Screen, db.session))
if __name__ == '__main__':
# Create DB
db.create_all()
# Start app
app.run(debug=True)
@ozanonurtek
Copy link

ozanonurtek commented Mar 12, 2018

Did you find a solution for this error? I run your code and facing with exact same problem, get_query function does not work properly. I open an question in StackOverflow, could you please help me if you find a solution for this.
https://stackoverflow.com/questions/49225520/flask-default-filters-with-hybrid-property

Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment