3.如何让计算字段可以排序

Django在模型属性的字段上添加了排序功能。 当您添加计算字段时,Django不知道如何执行order_by,因此不会在该字段上添加排序功能。 如果你想让计算字段也可以排序,你需要告诉Django如何去order_by 你可以在计算字段方法上设置admin_order_filed属性。

从之前的章节如何在django admin 中优化查询的页面中,添加如下:

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

修改了这些之后,你的admin就变成了这样:

  1. @admin.register(Origin)
  2. class OriginAdmin(admin.ModelAdmin):
  3. list_display = ("name", "hero_count", "villain_count")
  4. def get_queryset(self, request):
  5. queryset = super().get_queryset(request)
  6. queryset = queryset.annotate(
  7. _hero_count=Count("hero", distinct=True),
  8. _villain_count=Count("villain", distinct=True),
  9. )
  10. return queryset
  11. def hero_count(self, obj):
  12. return obj._hero_count
  13. def villain_count(self, obj):
  14. return obj._villain_count
  15. hero_count.admin_order_field = '_hero_count'
  16. villain_count.admin_order_field = '_villain_count'

3.如何让计算字段可以排序 - 图1