gpt4 book ai didi

python - 如何在 django admin 中使用自定义字段进行搜索

转载 作者:行者123 更新时间:2023-11-28 21:41:44 25 4
gpt4 key购买 nike

我有一个模型并已注册到管理员,我已使用自定义字段显示在列表中

class ReportsAdmin(admin.ModelAdmin):
def investment(self, inst):
return models.OrderDetail.objects.filter(user=inst.user).distinct().count()

list_display = ['investment']
search_fields = ['investment']

我想在 django admin 中使用 investment 字段进行搜索,但总是得到 Cannot resolve keyword 'investment' into field. 选择是模型字段。

有什么方法可以使用 investment 字段进行搜索吗?

最佳答案

在软件中,一切皆有可能... SMH 在已接受的答案中。您必须覆盖 get_search_results

from django.db.models import Count

class ReportsAdmin(admin.ModelAdmin):
def investment(self, inst):
return models.OrderDetail.objects.filter(user=inst.user).distinct().count()

list_display = ['investment']
search_fields = ['investment']

def get_search_results(self, request, queryset, search_term):
# search_term is what you input in admin site
search_term_list = search_term.split(' ') #['apple','bar']

if not any(search_term_list):
return queryset, False

if 'investment' in search_term_list:
queryset = OrderDetail.objects.annotate(
user_count=Count('user')
).filter(user_count__gte=search_term_list['investment'])

return queryset, False

关于python - 如何在 django admin 中使用自定义字段进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44432782/

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