0

I can't figure out how to make admin able to sort records using custom column - hours_to_deadline (when they clicks on the column header). In my case, it's timedelta.

class JobAdmin(SuperModelAdmin):
    ...
    list_display = ['id', 'identificator', 'created', 'invoice__estimated_delivery','hours_to_deadline','customer__username', 'language_from__name', 'language_to__name',
                    'delivery__status', 'confirmed', 'approved', 'invoice__final_price']
    ...


    def hours_to_deadline(self,obj):
        try:
            return (obj.invoice.estimated_delivery - now())
        except:
            return None

enter image description here

I found this solution: https://stackoverflow.com/a/15935591/3371056

But in my case, I can't just do sum or something similar.

Do you know what to do?

Community
  • 1
  • 1
Milano
  • 18,048
  • 37
  • 153
  • 353

2 Answers2

1

You cannot order by a field that is not an actual database field, because all the sorting is done on the database level. If it has a value related somehow to a database field you can do something like that in the model definition:

hours_to_deadline.admin_order_field = 'database_field'

You can read more about it at https://docs.djangoproject.com/en/1.10/ref/contrib/admin/

Roman B.
  • 189
  • 2
  • 8
-2

Answer is: ordering = ('-id',)

class JobAdmin(SuperModelAdmin):

    list_display = ['id', 'identificator', 'created', 'invoice__estimated_delivery','hours_to_deadline','customer__username', 'language_from__name', 'language_to__name',
                    'delivery__status', 'confirmed', 'approved', 'invoice__final_price']
    ordering = ('-id',)


    def hours_to_deadline(self,obj):
        try:
            return (obj.invoice.estimated_delivery - now())
        except:
            return None
Marin
  • 1,098
  • 14
  • 33