按属性值范围进行筛选



我有一个模型:

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(中做到这一点?

您可以使用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',并通过我们的自定义过滤器。

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

试试这个

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

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

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

喜欢:

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

最新更新