Flask-admin: Sorting select field (drop down)

Created on 2 Jun 2017  路  6Comments  路  Source: flask-admin/flask-admin

Is it possible to sort the items in a related field drop down (select field)?

This is the same question as closed issue #190, but the answer given only applied to sorting columns in list view.

I'm using Mongoengine.

Most helpful comment

I believe "query_factory" is a WTForm callable which only works with SQLAlchemy. Is that correct?

I'm using mongoengine (for MongoDB) instead of SQLAlchemy.

All 6 comments

Any updates on this guys?

I believe I ended up sorting on client side (browser).

@macfire that doesnt sound very ideal, but thanks for the suggestion

Better late than never.

`

class UserView(ModelView)
    def create_form(self):
        return self._use_filtered_dropdown(super(UserView, self).create_form())

    def edit_form(self, obj):
        return self._use_filtered_dropdown(super(UserView, self).edit_form(obj))

    def _use_filtered_dropdown(self, form):
        form.user.query_factory = self._get_sortable_dropdown_list
        return form

    def _get_sortable_dropdown_list(self):
        return self.session.query(User).order_by('second_name').all()

`

A simple way to do it in your view (code shows order_by and filter_by examples):

class MyView(sqla.ModelView):
  # normal view things...
  # the following shows a few order_by and filter examples:
  form_args = {
        "source_servers": {
            # filter to only show 'active' servers
            "query_factory": lambda: Server.query.filter_by(active=True).order_by(
                Server.name
            )
        },
        "target_server": {
            # filter to only show 'active' servers
            "query_factory": lambda: Server.query.filter_by(active=True).order_by(
                Server.name
            )
        },
        "run_by": {
            # order list by name.
            "query_factory": lambda: User.query.order_by(User.name)
        },
        "test_plan": {
            # order list by name.
            "query_factory": lambda: TestPlan.query.filter_by(active=True).order_by(
                TestPlan.name
            )
        },
        "test_date": {
            "format": "%Y-%m-%d %H:%M:%S"  # changes how the input is parsed by strptime (e.g. 2017-07-22 11:47:58).
        },
  }

I believe "query_factory" is a WTForm callable which only works with SQLAlchemy. Is that correct?

I'm using mongoengine (for MongoDB) instead of SQLAlchemy.

Was this page helpful?
0 / 5 - 0 ratings