Filter by a range of values of attribute

1.8k Views Asked by At

I have a model:

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

I need to create a filter on price such that I can input a price range (i.e. min_price=10, max_price=100) and it will give me products with price in that range.

Is there a way to do that in Django-admin (or Jet)?

3

There are 3 best solutions below

0
On BEST ANSWER

You can use ModelAdmin and override the get_search_results method, like this:

# 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

Now, if I input the string '20-25' it will search for title or price equals to '20-25', then search for price between the range 20 and 25. If I input the string '25' it will search for price or title equals to '25', and pass our custom filter.

You can find more about it here it in the docs.

0
On

Try this

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

Might be there is no option of such filters in Django admin(I am not sure). If there is an option then you have to customize the code. But you can use in views.py and show your results.

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

Like:

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