gpt4 book ai didi

python - 如何在 Django Admin 中按多种自定义方法排序

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:06 29 4
gpt4 key购买 nike

我希望能够在 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)。

如何修复它?

最佳答案

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

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

关于python - 如何在 Django Admin 中按多种自定义方法排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24670338/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com