Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow sorting in the Django admin by a custom list_display field, which doesn't have a DB field nor annotatable

I have a custom list_display field which is responsible for a column of integers in one of my admin pages.

I need to allow staff members to sort according to it.

There's a solution for how to acheive that if the integer represents a count/average/etc of some DB field, which is not the case for me.

[ the solution for that case is here: Django admin: how to sort by one of the custom list_display fields that has no database field ]

Any ideas how I can achieve this sorting without actually creating and maintaining a DB field for the values?

like image 465
GJ. Avatar asked Apr 15 '10 17:04

GJ.


1 Answers

The sorting is done at the DB Engine (in an order by clause), so I don't think you will be able to achieve what you want unless you materialize a field in the model. Computed states are not sortable at this point (at least not in the admin interface, if you were using your own interface you could use extra).

If the problem were filtering, you could write a custom FilterSpec (which doesn't appear to be documented anywhere, but SO has a good example).

But for sorting in the admin your only option is a materialized field, I'm afraid.

Edit:

Hmmm...

You could try something. It is possible (albeit I don't think it is documented anywhere formally) to change the queryset used by a ModelAdmin. If your computed field is simple enough to be embedded in the query itself you could do something like:

class BlahAdmin(admin.ModelAdmin):
    ... Whatever definitions ...

    def queryset(self, request):
        return Blah.objects.extra(select={'computed': "count(field_x)"})

This might work. It is untested though.

like image 168
cethegeek Avatar answered Nov 15 '22 09:11

cethegeek