Django — How to Order Inline ForeignKey

To apply ordering to a foreign key in the admin, you simply define an “ordering” attribute in your ModelAdmin.

But what about Inlines?

To apply ordering to an Inline Model’s foreign key, override the default form of the admin.StackedInline or admin.TabularInline subclass by specifying a ModelForm.

class OrderedInlineForm(forms.ModelForm):
    product = forms.ModelChoiceField(queryset=Product.objects.order_by('name'))
    class Meta:
        model = MyInlineModel

class MyInlineModelAdmin(admin.StackedInline):
    model = MyInlineModel
    form = OrderedInlineForm

1 Comment

  1. yufeng says:

    hello
    this method is good, but the form remove the ‘add’ jpg,so i can not add one referenced model in pop_win
    so could you add this functionality.
    thank you very much

Leave a reply to yufeng Cancel reply