views:

205

answers:

1

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: http://stackoverflow.com/questions/2168475/django-admin-how-to-sort-by-one-of-the-custom-list-display-fields-that-has-no-da ]

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

+1  A: 

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.

celopes