如何向具有多对一关系的模型的 Django 管理员添加可排序的计数列? [英] How to add a sortable count column to the Django admin of a model with a many-to-one relation?
问题描述
假设我有一个 Book 模型,其中包含一个 Publisher 模型的外键.
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屋!