Django Admin Cookbook-9如何启用对计算字段的排序

9.如何启用对计算字段的排序?

通常,Django会为模型属性字段,自动添加排序功能。当你添加计算字段时,Django不知道如何执行order_by,因此它不会在该字段上添加排序功能。

如果要在计算字段上添加排序,则必须告诉Django需要排序的内容。你可以通过在在计算字段方法中设置admin_order_field属性来执行此操作 。

我们从上一章(如何在Django admin中优化查询?)编写的Admin后台开始:

hero_count.admin_order_field = '_hero_count'
villain_count.admin_order_field = '_villain_count'

修改如下:

@admin.register(Origin)
class OriginAdmin(admin.ModelAdmin):
    list_display = ("name", "hero_count", "villain_count")

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(
            _hero_count=Count("hero", distinct=True),
            _villain_count=Count("villain", distinct=True),
        )
        return queryset
    def hero_count(self, obj):
        return obj._hero_count
    def villain_count(self, obj):
        return obj._villain_count
    hero_count.admin_order_field = '_hero_count'
    villain_count.admin_order_field = '_villain_count'

以下是Admin后台按hero_count排序的结果:

返回目录

猜你喜欢

转载自www.cnblogs.com/superhin/p/12171458.html