0
点赞
收藏
分享

微信扫一扫

Express与SQLite集成教程:轻松实现数据库操作

七公子706 2024-09-03 阅读 3

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

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

以OriginAdmin为例,添加以下代码

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'

显示效果:

后,点击抬头标签,显示字段排序

举报

相关推荐

0 条评论