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

后端 未结 1 1174
温柔的废话
温柔的废话 2020-12-19 10:23

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.

相关标签:
1条回答
  • 2020-12-19 11:12

    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.

    0 讨论(0)
提交回复
热议问题