There are two ordering
attributes that affect the default ordering in the Django Admin ChangeList
view.
The ModelAdmin.ordering
attribute, and the model's Meta.ordering
attribute.
# models.py
class Order(models.Model):
created_dt = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created_dt',)
# admin.py
class OrderAdmin(admin.ModelAdmin):
ordering = ('-created_dt',)
Both are a list or tuple specifying the default ordering for the change list.
If both a model's Meta.ordering
and ModelAdmin.ordering
are set, the ModelAdmin.ordering
will take precedence in the Django admin interface. This means that the ordering specified in the ModelAdmin
class will be used to order the items in the change list, overriding the ordering specified in the model's Meta
class.
Dynamically setting the default ordering for a ModelAdmin
:
class YourModelAdmin(admin.ModelAdmin):
def get_ordering(self, request):
# Specify the default ordering
if request.something:
return ['field1', 'field2']
return ['-created',]
To specify the list of columns that are allowed for sorting you can use the sortable_by
or dynamically via get_sortable_by
.
class YourModelAdmin(admin.ModelAdmin):
sortable_by = ['field1', 'field3']
# OR
def get_sortable_by(self, request):
# Specify the fields that are allowed to be used for sorting
return ['field1', 'field2']