[Solved]-Django Admin, sort with custom function


By following:

We can compose a solution to your problem:

from django.db.models import F

class ShotsAdmin(admin.ModelAdmin):
    list_display = ('get_ratio',)

    def get_queryset(self, request):
        qs = super(ShotsAdmin, self).get_queryset(request)
        qs = qs.annotate(ratio=F('hits') * 100 / F('all'))
        return qs

    def get_ratio(self, obj):
        return obj.ratio

    get_ratio.admin_order_field = 'ratio'


  • The get_queryset method will annotate a new field named ratio to
    your queryset. That field’s value is the application of your ratio function on the hits and all fields.
  • The get_ratio function returns the aforementioned field from a queryset instance.
  • Finally: get_ratio.admin_order_field = 'ratio' sets the ratio field as the ordering field for your queryset on the admin panel.

Leave a comment