88from .serializers import InventoryItemSerializer
99
1010class InventoryItemViewSet (viewsets .ModelViewSet ):
11- # This tells the view where to get the data and how to translate it
12- queryset = InventoryItem .objects .all ()
13- serializer_class = InventoryItemSerializer
11+ serializer_class = InventoryItemSerializer
12+
13+ def get_queryset (self ):
14+ # 1. Start with all items
15+ # does not talk to the database yet, its just a query plan
16+ queryset = InventoryItem .objects .all ()
17+
18+ # 2. Grab 'categories' from the URL (e.g., ?categories=Tools)
19+ category = self .request .query_params .get ('categories' )
20+
21+ # 3. Grab 'ordering' from the URL (e.g., ?ordering=name)
22+ sort_by = self .request .query_params .get ('ordering' )
23+
24+ # 4. Apply filters manually if the user provided them
25+ if category is not None :
26+ queryset = queryset .filter (categories = category )
27+
28+ # 5. Apply sorting manually
29+ if sort_by is not None :
30+ queryset = queryset .order_by (sort_by )
31+
32+ return queryset
33+
34+ # the original that works
35+ # class InventoryItemViewSet(viewsets.ModelViewSet):
36+ # # This tells the view where to get the data and how to translate it
37+ # queryset = InventoryItem.objects.all()
38+ # serializer_class = InventoryItemSerializer
0 commit comments