如何在Django Admin中按许多自定义方法排序

时间:2014-07-10 07:01:31

标签: python django django-admin

我希望能够通过Django Admin中的几种自定义方法进行排序。 This question仅为一种方法提供解决方案。

我试图修改它:

from django.db import models

class CustomerAdmin(admin.ModelAdmin):
    list_display = ('number_of_orders','number_of_somevalue') # added field

    def queryset(self, request):
        qs = super(CustomerAdmin, self).queryset(request)
        qs = qs.annotate(models.Count('order'))
        qs = qs.annotate(models.Count('somevalue')) # added line
        return qs

    def number_of_orders(self, obj):
        return obj.order__count
    number_of_orders.admin_order_field = 'order__count'

    def number_of_somevalue(self, obj): # added method
        return obj.somevalue__count
    number_of_somevalue.admin_order_field = 'somevalue__count'

它工作不正常。似乎它将count值相乘而不是单独计算它们。

示例:

我有2个订单和2个某些值,但在面板中我看到4个订单和4个某些值。

使用另一个值添加另一个方法使其为8(2 * 2 * 2)。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您可以尝试按许多自定义方法排序(已测试):

from django.db.models import Count

class CustomerAdmin(admin.ModelAdmin):

    # The list display must contain the functions that calculate values
    list_display = ('number_of_orders','number_of_somevalue') # added field

    # Overwrite queryset in model admin
    def queryset(self, request):
        qs = super(CustomerAdmin, self).queryset(request)
        # The query have to return multiple annotation, for this use distinct=True in the Count function
        qs = qs.annotate(number_orders = Count('order', distinct=True)).annotate(number_somevalue = Count('somevalue',distinct=True)) 
        return qs

    # This function return the new field calculated in queryset (number_orders)
    def number_of_orders(self, obj):
        return obj.number_orders

    number_of_orders.admin_order_field = 'numberorders' # sortable new column

    # And this one will return the another field calculated (number_somevalue)
    def number_of_somevalue(self, obj): # added method
        return obj.number_somevalue

    number_of_somevalue.admin_order_field = 'number_somevalue'# sortable new column