【问题标题】:Filter by a range of values of attribute按属性值范围过滤
【发布时间】:2020-01-20 11:04:14
【问题描述】:

我有一个模型:

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

【问题讨论】:

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


【解决方案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它。

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      【解决方案3】:

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

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

      喜欢:

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

      【讨论】:

      • 我认为它不是一个元组列表,但无论如何应该可以,+1
      • 它将返回 Products 对象的列表。如果我们使用values_list,那么它将返回tuple
      • docs它是一个元组,但我认为没关系
      • 在文档中没有提到返回元组。过滤器总是返回对象列表。
      • 当我说元组时,我的意思是你使用元组进行过滤,我知道它返回一个列表,Entry.objects.filter(pub_date__range=(start_date, end_date))
      猜你喜欢
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 2011-05-31
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 2012-06-17
      • 2023-03-12
      相关资源
      最近更新 更多