Skip to content

Commit 5c4d938

Browse files
authored
feat : adds sorting and filtering features to the products fetching API (#224)
* adds django filters to the REST_FRAMEWORK config * adds the core logic for filtering and sorting
1 parent 8ca16ef commit 5c4d938

2 files changed

Lines changed: 37 additions & 2 deletions

File tree

backend/core/settings/base.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,12 @@
4747
REST_FRAMEWORK = {
4848
'DEFAULT_AUTHENTICATION_CLASSES': (
4949
'rest_framework_simplejwt.authentication.JWTAuthentication',
50-
)
50+
),
51+
'DEFAULT_FILTER_BACKENDS': [
52+
'django_filters.rest_framework.DjangoFilterBackend',
53+
'rest_framework.filters.SearchFilter',
54+
'rest_framework.filters.OrderingFilter',
55+
],
5156
}
5257

5358
MIDDLEWARE = [

backend/products/views.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,42 @@
11
from rest_framework.generics import ListAPIView, RetrieveAPIView
2+
from rest_framework.filters import SearchFilter, OrderingFilter
3+
from django_filters.rest_framework import DjangoFilterBackend
4+
from django_filters import rest_framework as filters
25

36
from .models import Product
47
from .serializers import ProductSerializer
58

9+
class ProductFilter(filters.FilterSet):
10+
# simple text filters
11+
name = filters.CharFilter(lookup_expr='icontains')
12+
seller = filters.CharFilter(lookup_expr='icontains')
13+
tags = filters.CharFilter(lookup_expr='icontains')
14+
type = filters.CharFilter(lookup_expr='icontains')
15+
16+
# price range filters
17+
min_price = filters.NumberFilter(field_name="price", lookup_expr='gte')
18+
max_price = filters.NumberFilter(field_name="price", lookup_expr='lte')
19+
20+
# exact match filters
21+
category = filters.ChoiceFilter(choices=[('clothing', 'Clothing'), ('rsvp', 'RSVP')])
22+
color = filters.CharFilter(lookup_expr='iexact')
23+
size = filters.CharFilter(lookup_expr='iexact')
24+
25+
class Meta:
26+
model = Product
27+
fields = ['name', 'seller', 'tags', 'type', 'category', 'color', 'size']
28+
629
class ListProductView(ListAPIView):
730
queryset = Product.objects.all()
831
serializer_class = ProductSerializer
32+
filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
33+
filterset_class = ProductFilter
34+
35+
search_fields = ['name', 'description', 'tags', 'seller', 'type']
36+
37+
ordering_fields = ['name', 'price', 'created_at', 'seller']
38+
ordering = ['-created_at']
939

1040
class RetrieveProductView(RetrieveAPIView):
1141
queryset = Product.objects.all()
12-
serializer_class = ProductSerializer
42+
serializer_class = ProductSerializer

0 commit comments

Comments
 (0)