Django admin:如何通过自定义方法对列进行排序

时间:2013-04-02 09:04:21

标签: django django-admin

 class Item(models.Model):
     name = models.CharField(max_length=100, unique=True)

     def admin_amount(self):
         total = self.warehouse_set.all().aggregate(item=Sum('amount'))
         return total['item']

 class Warehouse(models.Model):
     name = models.CharField(max_length=100, unique=True)
     item = models.ForeignKey('Item', blank=True, null=True)
     amount = models.IntegerField()

创建新字段是错误的,但我不能做类似的事情:

 admin_amount.admin_order_field = 'admin_amount'

我找到了similar question但是我遇到了重写queryset()方法的问题(无法编写类似qs.warehouse_set.all().annotate(models.Sum('amount'))的内容)。有没有办法为我或我的情况调整这个解决方案,还有另一种解决方案吗?

1 个答案:

答案 0 :(得分:18)

使用the linked question(以及suggested edit)中的代码,底部应该为您的示例执行此操作。原理是使用annotate将子查询中的其他数据添加到返回的QuerySet。在这种情况下,仓库中的金额为Sum

接下来,添加一个包装函数amount_in_warehouses以获取每行的此值,并告诉管理员显示此列表list_display = ('amount_in_warehouses',),并对其进行排序amount_in_warehouses.admin_order_field = 'amount_in_warehouses'

class ItemAdmin(admin.ModelAdmin):
    list_display = ('amount_in_warehouses',)
    name = models.CharField(max_length=100, unique=True)

    def queryset(self, request):
        qs = super(ItemAdmin, self).queryset(request)
        qs = qs.annotate(models.Sum('warehouse__amount'))
        return qs

    def amount_in_warehouses(self, obj):
        return obj.warehouse__amount__sum
    amount_in_warehouses.admin_order_field = 'amount_in_warehouses'