开发者

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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜