如何在Django管理中按值列表过滤?

时间:2019-11-12 21:23:22

标签: python django filter

如何通过用户在文本字段中输入的值列表来过滤Django Admin中的对象?

例如-用户输入用逗号分隔的ID列表,而Django Admin应该返回所有与这些ID匹配的对象?

1 个答案:

答案 0 :(得分:0)

这是概念,因此您应该根据需要进行更改

class YourAdmin(admin.ModelAdmin):
    list_display = ['id']
    search_fields = ['id']

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset, search_term)
        if search_term != '': # This chek needed if you additionaly use SimpleListFilter, otherwise SimpleListFilter would be broken
            search_term = map(int, search_term.split(',')) #not integers in search_term will result in an error
            queryset |= self.model.objects.filter(id__in = search_term)
        return queryset.distinct(), use_distinct #adding distinct() or objects duplicates could appear

我的项目结果

enter image description here