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?

user2672932
  • 339
  • 1
  • 2
  • 10

1 Answers1

48

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.

Prakhar Trivedi
  • 8,218
  • 3
  • 28
  • 35
Rachel Sanders
  • 5,734
  • 1
  • 27
  • 36
  • 3
    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 :) – user2672932 Oct 14 '14 at 12:29
  • Awesome, I'm so glad! – Rachel Sanders Oct 14 '14 at 17:59
  • 1
    @RachelSanders: Updated your answer to include user's comment, hope that's OK. Thanks for researching this, it really helped me out! – Christian Aichinger Jun 12 '15 at 21:05
  • @RachelSanders Since you seem to be a flask-admin pro: just in case you know the answer, I started a bounty on [this question](http://stackoverflow.com/q/33660840). :) – Hans Schindler Nov 14 '15 at 00:19
  • 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. – Julien Garcia Mar 19 '21 at 11:01
  • I can't seem to figure out how to filter by a property of a relationship of the model... any clues? – kontur Dec 10 '21 at 11:47