Reputation: 129
I have the following Django view in my Django Rest-Framework API
from django_filters.rest_framework import DjangoFilterBackend, RangeFilter, FilterSet
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework import generics
from api.serializers import UserSerializer
from django.contrib.auth.models import User
from rest_framework import permissions
from api.permissions import IsOwnerOrReadOnly
from MyGameDBWebsite.models import Game, GameDeveloper, GameGenre, GameConsole
from api.serializers import GameSerializer, DeveloperSerializer, GenreSerializer, ConsoleSerializer
class GameList(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
serializer_class = GameSerializer
filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter,)
filter_fields = ('owner__username', 'id', 'game_title', 'game_developer_name', 'game_console',
'game_genre', 'game_release_year', 'game_price',)
ordering_fields = ('owner__username', 'id', 'game_title', 'game_developer_name', 'game_console',
'game_genre', 'game_release_year', 'game_price',)
search_fields = ('game_title', 'game_release_year', 'game_price',)
queryset = Game.objects.all()
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
My output URL is the following: http://127.0.0.1:8000/api/?owner__username=&id=&game_title=&game_developer_name=&game_console=&game_genre=&game_release_year=&game_price=
I want create a price range so that i can call the API from URL to get the results in a price range
Upvotes: 2
Views: 1940
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 Game
from myapp.serializers import GameSerializer
from rest_framework import generics
class GameListFilter(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 = Game
fields = ['min_price', 'max_price']
class GameList(generics.ListAPIView):
queryset = Game.objects.all()
serializer_class = GameSerializer
filter_class = GameListFilter
Which will allow you to make requests such as:
http://example.com/api/games?max_price=8.00
Upvotes: 0
Reputation: 88499
You should define a filterset_class
and use it in your views.
In the case of RangeFilter
, You should define your price field with RangeFilter
class GameFilter(filters.FilterSet):
game_price = filters.RangeFilter()
class Meta:
model = Game
fields = ['game_price']
and hence your url will be as, /api/?game_price_min=123&game_price_max=321
Upvotes: 3