Well, I've missed 10-11 before. No wonder I started to look confused when I saw 6.5 in the video
Continue
class GoodsListViewset(mixins.ListModelMixin, viewsets.GenericViewSet): """ //Product list page """ serializer_class = GoodsSerializer pagination_class = GoodsPagination # Because GenericViewSet also calls the get ﹣ queryset function to get the model def get_queryset(self): return Goods.objects.filter(shop_price__gt = 100)
In this way, you can filter the data whose commodity price is more than 100 yuan
But it's too rigid to write like this
def get_queryset(self): # This all() does not get a large amount of data, but only generates sql commands to get all the data until iteration queryset = Goods.objects.all() # Price? Min is the field obtained by the front end price_min = self.request.query_params.get('price_min', 0) if price_min: queryset = queryset.filter(shop_price__gt = int(price_min)) return queryset
Effect:
Further use of filtering:
DjangoFilterBackend
SearchFilter
OrderingFilter
Install Django filter first
Then add
INSTALLED_APPS = ['django_filters']
views.py:
from django_filters.rest_framework import DjangoFilterBackend class GoodsListViewset(mixins.ListModelMixin, viewsets.GenericViewSet): """ //Product list page """ # Get? Queryset function is not needed queryset = Goods.objects.all().order_by('id') serializer_class = GoodsSerializer pagination_class = GoodsPagination filter_backends = (DjangoFilterBackend,) filter_fields = ('name', 'shop_price')
Effect:
After clicking:
If this filtering function is not satisfied, you can customize a filter file and class
This completes the function of data filtering
# filter.py import django_filters from django.db.models import Q from .models import Goods # Inheritance class of Django 2.0 class GoodsFilter(django_filters.rest_framework.FilterSet): """ //Filter category of goods """ # Note here that after 2.0, it was changed to field "name" instead of "name" price_min = django_filters.NumberFilter(field_name='shop_price', lookup_expr='gte') price_max = django_filters.NumberFilter(field_name='shop_price', lookup_expr='lte') class Meta: model = Goods fields = ['price_min','price_max'] #views.py from .filters import GoodsFilter class GoodsListViewset(mixins.ListModelMixin, viewsets.GenericViewSet): """ //Product list page """ queryset = Goods.objects.all().order_by('id') serializer_class = GoodsSerializer pagination_class = GoodsPagination filter_backends = (DjangoFilterBackend,) filter_class = GoodsFilter
End