django admin 在列表视图中对计算字段进行排序

django admin sort calculated fields in listview

我有两个模型,一个(设备)有另一个(存储)的外键。在存储的管理概述中,我希望能够添加一个计数,说明有多少设备指向每个存储。使用下面的代码,我能够正确计算指向每个存储的设备数量。但是,当尝试按存储中的数字排序时,它会崩溃并出现以下错误:

Cannot resolve keyword '_get_device_number' into field. Choices are: ... #List of fields

如何将我的计算字段添加到允许搜索的列表中?

class Device(models.Model):
...
storage_id = models.ForeignKey(Storage, on_delete=models.PROTECT, blank=True,null=True) #Allowed to be null since a Device may not be in storage.

class Storage(models.Model):
...
    def _get_device_number(self,):
        return Device.objects.filter(storage_id=self.storage_id).count()

class StorageAdmin(admin.ModelAdmin):
...
    list_display = ['__str__', 'get_device_number',]

    def get_device_number(self, obj):
        return obj._get_device_number()
get_device_number.admin_order_field = '_get_device_number'

管理员列表视图无法访问模型方法。但是,注释管理查询集确实有效。

class StorageAdmin(admin.ModelAdmin):

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(
            _get_device_number=Count('device')
        )

        return queryset

    def get_device_number(self, obj):
        return obj._get_device_number

    get_device_number.admin_order_field = '_get_device_number'