DRF 学习笔记

DRF View

Model

from django.db import model

serializer.Serializer  比这个更好的是  serializer.ModelSerializer 

下面是可以继承的mixin

mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,

他们分别对应的前端请求是 比如说 axios.patch

post
get + id 
patch
delete
get + 参数

这是通用的

GenericViewSet 

这是是终极大boss

ModelViewSet

关于过滤

下面是重写 get_queryset 方式获取的过滤功能

def get_queryset(self):
    q = MyApartment.objects.all()

    price_min = self.request.query_params.get("price_min", 0) # 0 是默认值

    if price_min:
        queryset = q.filter(price__gt=int(price_min)) #django 语法
        return queryset

下面是使用filter 文件来过滤

class Roomfilters(django_filters.rest_framework.FilterSet):
'''
房间的过滤类
'''
price_min = django_filters.NumberFilter(name='price',lookup_expr='gte')
price_max = django_filters.NumberFilter(name='price',lookup_expr='lt')
district = django_filters.CharFilter(name='district',lookup_expr='icontains') #前面加i忽略大小写

class Meta:
    model = MyApartment
    fields = ['price_min','price_max','district']

搜索

filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)

search_fields = ('district','rooms')  # ^[email protected]$ 分别代表 startwith /exact match/Full search/ regex

排序

filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)

ordering_fields = ('price')