Reputation: 168
I have a model Item
with field price
.
class Item(models.Model):
title = models.CharField(max_length=200, blank='true')
price = models.IntegerField(default=0)
My query may contain min_price
& max_price
values. So, my request may be like this: http://example.com/api/items?min_price=50&max_price=500
. Can anybody tell me, how can I query items between min & max values? Can I solve it using Django ORM?
Thanks!
Upvotes: 3
Views: 9292
Reputation: 190
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
Upvotes: 1