Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Order_by for relationship ? #190

Closed
nMustaki opened this issue Mar 18, 2013 · 3 comments
Closed

Order_by for relationship ? #190

nMustaki opened this issue Mar 18, 2013 · 3 comments

Comments

@nMustaki
Copy link
Contributor

Hi,
I have two tables, link by a relationship :

class News(db.Model):
   #[...]
    venue_id = db.Column(db.Integer(), db.ForeignKey(Venue.id))
    venue = db.relationship(Venue, backref='news')

When creating a News item, venue objects are displayed in a select, but there are not ordered, how could I do that ?

Thanks you !

@mrjoes
Copy link
Member

mrjoes commented Mar 19, 2013

All you have to do is to tell Flask-Admin which field to use for sorting. By default Flask-Admin won't make any assumptions about it.

This is snippet from sqla:

class PostAdmin(sqlamodel.ModelView):
    # List of columns that can be sorted. For 'user' column, use User.username as
    # a column.
    column_sortable_list = ('title', ('user', User.username), 'date')

user is relation to the User table. If you wish, you can point it to User.id too.

@mrjoes mrjoes closed this as completed Mar 19, 2013
@mistercrunch
Copy link

This seems to affect what is sortable in the list view. What about managing the sort order in the (dropdown) on the edit view? I can't get those sorted.

@sampart
Copy link

sampart commented Mar 4, 2019

@mistercrunch (and others who find this via Google like me), you could update the query_factory property on the form field. Something like this:

    def edit_form(self, obj=None):
        form = super().edit_form(obj)

        # apply a sort to the relation
        form.venue.query_factory = lambda: models.Venue.query.order_by(models.Venue.name)

        return form

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants