How can I sort by calculated fields in Django Admin?

I have a calculated method in my model, and in admin page want to add sort functionality for that calculated field.

For now, I am using aggregation for model calculated fields and displaying that in admin. How can I add sort function for this field in admin page?

class CoinWallet(Account):
    student = models.OneToOneField(
        'students.Student',
        on_delete=models.PROTECT,
        related_name="coinWallet",
        null=True)

    @admin.display(description='Total Coins')
    def total_coins(self):

        positive_movements_aggregate = self.movement_set.filter(
            side=self.positive_side,
        ).aggregate(models.Sum('amount'))

        positive_movements_balance = positive_movements_aggregate[
            'amount__sum'] if positive_movements_aggregate['amount__sum'] else 0

        return f'{positive_movements_balance}'

@admin.register(CoinWallet)
class CoinWalletAdmin(admin.ModelAdmin):
    list_display = ('id', 'student', 'balance', 'total_coins', 'answer_coins', 'bonus_coins', )
    search_fields = ('id', 'student')

    def get_queryset(self, request):
        queryset = super(CoinWalletAdmin, self).get_queryset(request)
        queryset = queryset.annotate(_total_coins=ExpressionWrapper(F('balance'), output_field=DecimalField())).order_by('_total_coins')
        return queryset
    def total_coins(self, obj):
        return obj._total_coins
    total_coins.admin_order_field = '_total_coins'

I tried this, but, instead of balance, i want to add sortable for total_coins. What should I do in this admin class?

use order_by instead:

class CoinWalletAdmin(admin.ModelAdmin):
    ...
    def get_queryset(self, request):
        qs = super(CoinWalletAdmin, self).get_queryset(request)
        qs = qs.order_by(F('total_coins')
        return qs
Back to Top