如何允许在 Django 管理员中通过自定义 list_display 字段进行排序,该字段没有 DB 字段,也没有可注释 [英] How to allow sorting in the Django admin by a custom list_display field, which doesn't have a DB field nor annotatable

查看:14
本文介绍了如何允许在 Django 管理员中通过自定义 list_display 字段进行排序,该字段没有 DB 字段,也没有可注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义 list_display 字段,它负责我的一个管理页面中的一列整数.

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.

如果整数表示某个 DB 字段的计数/平均值/等,有一个解决方案来解决这个问题,而我的情况并非如此.

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.

[该案例的解决方案在这里:Django 管理员:如何按没有数据库字段的自定义 list_display 字段之一进行排序]

[ 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?

推荐答案

排序是在 DB 引擎中完成的(在 order by 子句中),所以我认为你无法实现你想要的,除非你在模型中实现一个字段.此时计算状态不可排序(至少在管理界面中不可排序,如果您使用自己的界面,则可以使用 额外).

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).

如果问题是过滤,您可以编写自定义 FilterSpec(似乎没有在任何地方记录,但 SO 有一个 好例子).

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.

嗯……

你可以试试.有可能(虽然我不这么认为正式记录在任何地方)以更改 ModelAdmin 使用的查询集.如果您的计算字段足够简单,可以嵌入到查询本身中,您可以执行以下操作:

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.

这篇关于如何允许在 Django 管理员中通过自定义 list_display 字段进行排序,该字段没有 DB 字段,也没有可注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆