[Django]-How to filter objects by price range in Django?

11👍

Check api reference for range. Like it states

You can use range anywhere you can use BETWEEN in SQL — for dates,
numbers and even characters.

So, in your case:

Item.objects.filter(price__range=(min_price, max_price))
👤Yasel

1👍

Specifying a FilterSet
For more advanced filtering requirements you can specify a FilterSet class that should be used by the view. For example:

import django_filters
from myapp.models import Item
from myapp.serializers import ItemSerializer
from rest_framework import generics


class ItemListFilter(django_filters.FilterSet):
min_price = django_filters.NumberFilter(name="price", lookup_type='gte')
max_price = django_filters.NumberFilter(name="price", lookup_type='lte')
class Meta:
    model = Item
    fields = ['min_price', 'max_price']


class ItemList(generics.ListAPIView):
queryset = Item.objects.all()
serializer_class = GameSerializer
filter_class = ItemListFilter

Which will allow you to make requests such as:

http://example.com/api/games?min_price=1.20&max_price=8.00
👤Talita

Leave a comment