按一系列属性值过滤

时间:2019-09-19 12:00:15

标签: python django filter django-admin django-jet

我有一个模特:

class Product(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    amount = models.IntegerField()
    price = models.FloatField()

我需要创建一个价格过滤器,以便我可以输入价格范围(即min_price = 10,max_price = 100),它将为我提供价格在该范围内的产品。

在Django-admin(或Jet)中是否可以做到这一点?

3 个答案:

答案 0 :(得分:1)

尝试一下

    filtered_products = Product.objects.all().filter(price__range=(min_price, max_price))

答案 1 :(得分:1)

在Django admin中可能没有此类过滤器的选项(我不确定)。如果有一个选项,那么您必须自定义代码。但是您可以在views.py中使用并显示结果。

products = Products.objects.filter(price__range=[min_price, max_price])

赞:

products = Products.objects.filter(price__range=[10, 100])

答案 2 :(得分:1)

您可以使用ModelAdmin并覆盖get_search_results方法,如下所示:

# your_app/admin.py
from django.contrib import admin
from .models import Product

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('title', 'amount', 'price')
    search_fields = ('title', 'price')  # this will create a text input for filtering title and price

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset, search_term)

        # You need to define a character for splitting your range, in this example I'll use a hyphen (-)
        try:
            # This will get me the range values if there's only 1 hyphen
            min_price, max_price = search_term.split('-')
        except ValueError:
            # Otherwise it will do nothing
            pass
        else:
            # If the try was successful, it will proceed to do the range filtering
            queryset |= self.model.objects.filter(price__gte=min_price, price__lte=max_price)
        return queryset, use_distinct

现在,如果我输入字符串'20-25',它将搜索标题或价格等于'20-25'的价格,然后搜索20到25之间的价格。 如果我输入字符串'25',它将搜索等于'25'的价格或标题,并通过我们的自定义过滤器。

您可以在文档中here中找到有关它的更多信息。