Django admin: how to sort column by custom method

前端 未结 1 1549
孤街浪徒
孤街浪徒 2020-12-28 18:24
 class Item(models.Model):
     name = models.CharField(max_length=100, unique=True)

     def admin_amount(self):
         total = self.warehouse_set.all().aggregat         


        
相关标签:
1条回答
  • 2020-12-28 18:57

    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.

    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'
    
    0 讨论(0)
提交回复
热议问题