How to sort by custom field in Django admin

from django.db import models

class SomeAdmin(admin.ModelAdmin):
    list_display = ('db_field', 'custom_field',)

    def queryset(self, request):
        qs = super(SomeAdmin, self).queryset(request)
        qs = qs.annotate(models.Count('movies'))
        return qs

    def custom_field(self, obj):
        return 'Total movies {0}'.format(obj.movies__count)
    custom_field.admin_order_field = 'movies__count'
    custom_field.short_description = 'Movies'
comments powered by Disqus