如何向具有多对一关系的模型的Django管理员添加可排序计数列? [英] How to add a sortable count column to the Django admin of a model with a many-to-one relation?
问题描述
假设我有一个包含发布商模型的外键的图书模型。
Suppose I have a Book model containing a foreign key to a Publisher model.
如何在Django管理员中显示一列,其中出版的图书数量每个发行商,我可以使用内置的排序方式?
How can I display in the Django admin a column with the number of books published by each publisher, in a way that I can use the built-in sorting?
推荐答案
我有同样的问题(我不能改变我的模型的经理添加缓慢的注释或连接)。这两个答案的组合在这里工作。 @Andre真的很接近,Django Admin支持修改只有管理员的查询集,所以在这里应用相同的逻辑,然后使用admin_order_field属性。当然,您仍然需要将新的管理员字段添加到list_display。
I had the same issue (I cannot change my model's manager to add slow annotations or joins). A combination of two of the answers here works. @Andre is really close, the Django Admin supports modifying the queryset for just the admin, so apply the same logic here and then user the admin_order_field attribute. You still need to add the new admin field to list_display, of course.
from django.db.models import Count
class EventAdmin(admin.ModelAdmin)
list_display = (..., 'show_artist_count')
def queryset(self, request):
# def get_queryset(self, request): for Django 1.6+
qs = super(EventAdmin, self).queryset(request)
return qs.annotate(artist_count=Count('artists'))
def show_artist_count(self, inst):
return inst.artist_count
show_artist_count.admin_order_field = 'artist_count'
这篇关于如何向具有多对一关系的模型的Django管理员添加可排序计数列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!