如何允许在 Django 管理中通过自定义 list_display 字段进行排序,该字段没有数据库字段,也没有可注释的字段
我有一个自定义 list_display 字段,它负责我的一个管理页面中的一列整数。
我需要让工作人员根据它进行排序。
如果整数表示某些数据库字段的计数/平均值/等,则有一个解决方案,但对我来说并非如此。
[这种情况的解决方案在这里:Django 管理:如何按没有数据库字段的自定义 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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
排序是在数据库引擎中完成的(按 order by 子句),因此我认为除非您在模型中具体化一个字段,否则您将无法实现您想要的目标。此时计算的状态不可排序(至少在管理界面中不可排序,如果您使用自己的界面,则可以使用 额外)。
如果问题是过滤,您可以编写一个自定义 FilterSpec (似乎没有在任何地方记录,但 SO 有一个 好例子)。
但恐怕要在管理中进行排序,您唯一的选择是物化字段。
编辑:
嗯...
你可以尝试一些东西。 有可能(尽管我不认为已在任何地方正式记录)以更改模型管理员使用的查询集。如果您的计算字段足够简单,可以嵌入到查询本身中,您可以执行以下操作:
这可能有效。但它尚未经过测试。
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:
This might work. It is untested though.