Flask-Admin default filters
Asked Answered
D

1

21

I would like to display only paid orders in my Flask-Admin model list view.

Here is models.py:

class Order(db.Model):
   id = db.Column(db.Integer, primary_key=True)
   amount = db.Column(db.Integer)
   description = db.Column(db.String)
   paid = db.Column(db.Boolean, default=False)

Here is ModelView for Flask-Admin:

class OrderView(ModelView):
    column_filters = ("paid")


admin.add_view(OrderView(Order, db.session))

Filters work fine, but I would like to make this filter default. Or better yet, do not use filters, and only show orders that are output of Order.query.filter(Order.paid==True) query.

Is it possible to do with Flask-Admin?

Darrondarrow answered 13/10, 2014 at 22:18 Comment(0)
P
50

We do this in our app by overriding ModelView.

https://github.com/mrjoes/flask-admin/blob/master/flask_admin/contrib/sqla/view.py#L654

I looked through the source code a bit for Flask-Admin, and they've made the API easier to use since we last edited this code because it looks like you can just do:

from flask.ext.admin.contrib.sqla.view import ModelView, func

class PaidOrderView(ModelVew):
    def get_query(self):
      return self.session.query(self.model).filter(self.model.paid==True)

    def get_count_query(self):
      return self.session.query(func.count('*')).filter(self.model.paid==True)

(We were overriding get_list() which is not nearly as great.)

You can then use it like:

admin.add_view(PaidOrderView(Order, db.session))

Let me know if that doesn't work for you and I can take another look.

Phosphoroscope answered 14/10, 2014 at 0:41 Comment(6)
It works great, thank you very much! Although I had to change query count function to "def get_count_query(self): return self.session.query(func.count('*')).filter(Order.paid==True)" , otherwise it was giving an error, something about Int object not having scalar attribute :)Darrondarrow
Awesome, I'm so glad!Phosphoroscope
@RachelSanders: Updated your answer to include user's comment, hope that's OK. Thanks for researching this, it really helped me out!Jampan
@RachelSanders Since you seem to be a flask-admin pro: just in case you know the answer, I started a bounty on this question. :)Tazza
For Flask mongo dev passing by, it worth mentioning that if you use Pymongo instead then you could overide your get_list function and tweak the filter argument in there.Spectre
I can't seem to figure out how to filter by a property of a relationship of the model... any clues?Benzene

© 2022 - 2024 — McMap. All rights reserved.