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

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

问题描述

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



我需要允许工作人员根据它进行排序



有一个如何实现的解决方案,如果整数表示某个DB字段的count / average / etc,对我来说不是这样。 >

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



任何想法如何实现此排序,而不实际创建和维护值的DB字段?

解决方案

排序是在DB Engine(按子句的顺序)完成的,所以我认为除了在模型中实现一个字段之外,我不认为你将能够实现你想要的。计算状态在这一点上是不可排序的(至少在管理界面中,如果您使用自己的界面,可以使用 extra



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



但是,在管理员中排序您唯一的选择是一个物化场,恐怕。



编辑:



嗯..



你可以尝试一下。 可能(尽管我不认为它在任何地方正式记录)来更改ModelAdmin使用的查询器。如果您的计算字段足够简单,可嵌入查询本身,您可以执行以下操作:

  class BlahAdmin(admin.ModelAdmin )
...无论什么定义...

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

这可能会工作。这是未经测试的。


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.

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

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