Django — Ordering Admin / ModelAdmin Inlines

Ordering admin inlines is a common problem with a not so documented fix that I created. Even the BaseInlineFormSet.get_queryset() isn’t documented. By the way, it’s ever so slightly confusing that managers use `get_query_set` and this uses `get_queryset`.

To order admin inlines, specify the FormSet used by the Inline and override get_queryset() in your formset definition with ordering.

from django.forms.models import BaseInlineFormSet

class OrderedFormSet(BaseInlineFormSet):
    def get_queryset(self):
        return super(OrderedFormset, self).get_queryset().order_by('-sortfield')

class MyInline(admin.TabularInline):
    model = Item
    formset = OrderedFormSet

3 thoughts on “Django — Ordering Admin / ModelAdmin Inlines

  1. Nice. Thanks.
    Maybe you know another trick..

    I am editing an organization and have roles in that organization as TabularInline. Every role is assigned to a person with a ForeignKey relation to the Person model. So in the admin form for each role I have a select box with all the persons in the database, but unfortunately the persons in the select list are not sorted by name.

    Maybe you have an idea how I can sort them?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s