Django admin:如何通过自定义方法对列进行排序 [英] Django admin: how to sort column by custom method

查看:59
本文介绍了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()

创建新字段是错误的,但我不能这样做:

Create new field is wrong, but I cant do something like:

 admin_amount.admin_order_field = 'admin_amount'

我发现 类似问题 但我遇到了重写 queryset() 方法的问题(不能写类似 qs.warehouse_set.all().annotate(models.Sum('amount'))).有没有办法为我调整这个解决方案,或者就我而言,还有另一种解决方案?

I found similar question but I encountered a problem with rewriting queryset() method(can't write something like qs.warehouse_set.all().annotate(models.Sum('amount'))). Is there any way to adapt this solution for me or in my case, there is another solution?

推荐答案

使用 链接问题(以及 建议编辑),底部应该为您的示例执行此操作.其原理是使用annotate 将来自子查询的附加数据添加到返回的QuerySet 中.在本例中为仓库中金额的Sum.

Using the code in the linked question (and the suggested edit), the bottom should do it for your example. The principle is to use annotate to add additional data from a sub-query to the returned QuerySet. In this case the Sum of the amounts in warehouses.

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

Next you add a wrapper function amount_in_warehouses to get this value out for each row, and tell the admin to show this for listing list_display = ('amount_in_warehouses',), and sort on it 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'

这篇关于Django admin:如何通过自定义方法对列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆