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.