Filtering and Ordering in Django
DRF includes filters and ordering classes that can be used to filter and order result sets. Here's an example view that filters books by author:
python
from rest_framework import generics, filters
from .models import Book
from .serializers import BookSerializer
class BookList(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['author']
In this example, we specify the SearchFilter class as the filter backend and the author field as the search field. This allows clients to filter the result set by author using the ?search= query parameter.
We can also order the result set by adding the OrderingFilter class:
python
class BookList(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_backends = [filters.SearchFilter, filters.OrderingFilter]
search_fields = ['author']
ordering_fields = ['title', 'pub_date']
In this example, we specify the OrderingFilter class as the ordering backend and the title and pub_date fields as the ordering fields. This allows clients to order the result set by title or publication date using the ?ordering= query parameter.
No comments:
Post a Comment