Django admin:反向FK聚合的SORTING list_display字段

时间:2017-04-07 12:45:08

标签: python django

模型 Station 有一个FK到系统。我想将 Station 计数显示为系统管理员更改列表中的列。我已经使用下面的代码实现了这个目标,但是我很难做出这样的数字'列可排序。

model.py:

class System(models.Model):
    pass

class Station(models.Model):
   system_info = models.ForeignKey(System)

admin.py:

class SystemAdmin(admin.ModelAdmin):
    def num_stations(self, obj):
        return obj.station_set.count()

    # num_stations.admin_order_field = ????
    num_stations.short_description = 'stations'

    list_display = (num_stations',)

普通的&#station; set_set'反向关系的语法似乎在admin_order_field中不起作用,即使其他堆栈溢出问题通常显示遍历正向关系也是如此 例如

1 个答案:

答案 0 :(得分:1)

感谢Alasdair的评论,答案是this question所指出的。这是适合我的问题的解决方案:

class SystemAdmin(admin.ModelAdmin):
    def num_stations(self, obj):
        return obj.num_stations

    def get_queryset(self, request):
        # def queryset(self, request): # For Django <1.6
        qs = super(SystemAdmin, self).get_queryset(request)
        # qs = super(CustomerAdmin, self).queryset(request) # For Django <1.6
        qs = qs.annotate(num_stations=Count('station'))
        return qs

    num_stations.admin_order_field = 'num_stations'
    num_stations.short_description = 'stations'

    list_display = ('num_stations', )