14👍
✅
By following:
- The accepted answer to this post:
Django admin: how to sort by one of the custom list_display fields that has no database field - The
How to execute arithmetic operations between Model fields in django
(Disclaimer: I have composed that Q&A style example)
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'
Explanation:
- The
get_queryset
method will annotate a new field namedratio
to
your queryset. That field’s value is the application of your ratio function on thehits
andall
fields. - The
get_ratio
function returns the aforementioned field from a queryset instance. - Finally:
get_ratio.admin_order_field = 'ratio'
sets theratio
field as the ordering field for your queryset on the admin panel.
Source:stackexchange.com