DRF安装
pip install djangorestframework
pip install markdown # 可选依赖包
pip install django-filter # 可选依赖包
DRF配置
INSTALLED_APPS = (
...
'rest_framework',
'django_filters',
)
DRF基础
#model.py
class GoodsCategory(models.Model):
"""
商品类别
"""
CATEGOTY_TYPE = (
(1, '一级类目'),
(2, '二级类目'),
(3, '三级类目'),
)
name = models.CharField(default='', max_length=30, verbose_name='类别名', help_text='类别名')
code = models.CharField(default='', max_length=30, verbose_name='类别code', help_text='类别code')
desc = models.TextField(default='', verbose_name='类别描述', help_text='类别描述')
category_type = models.IntegerField(choices=CATEGOTY_TYPE, verbose_name='类别级别', help_text='类别级别')
parent_category = models.ForeignKey("self", null=True, blank=True, verbose_name='父类目级别', help_text='父类目级别',
related_name='sub_cat', on_delete=models.SET_NULL)
is_tab = models.BooleanField(default=False, verbose_name='是否导航', help_text='是否导航')
add_time = models.DateField(default=datetime.now, verbose_name='添加时间')
class Meta:
verbose_name = "商品类别"
verbose_name_plural = verbose_name
def __str__(self):
return self.name
#app.urls.py
from django.urls import path, include
from goods import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('categorys', views.CategoryListViewSet)
router.register('', views.GoodsListViewSet)#复杂路由放前面,简单路由放在最后
app_name = 'goods'
urlpatterns = [
path('', include(router.urls)),
]
#serializer.py
from rest_framework import serializers
from goods import models
class GoodsCategorySerializer(serializers.ModelSerializer):
class Meta:
model = models.GoodsCategory
fields = '__all__'
#view.py
from rest_framework import viewsets, mixins
from rest_framework import filters
from django_filters import rest_framework as r_filters
from goods.models import Goods
from goods import serializers
class GoodsListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
"""
商品列表页
"""
#最基础配置
queryset = Goods.objects.all()
serializer_class = serializers.GoodsSerializer
#过滤配置
filter_backends = (filters.SearchFilter, r_filters.DjangoFilterBackend)
filterset_class = GoodsFilter
search_fields = ['name']
#分页配置
pagination_class = GoodsPagination
过滤器
#filter.py
from django_filters import rest_framework as r_filters
from rest_framework import filters
from django.db.models import Q
class GoodsFilter(r_filters.FilterSet):
"""
过滤器
"""
min_price = r_filters.NumberFilter(field_name="shop_price", lookup_expr='gte', label='最小商品价格')
max_price = r_filters.NumberFilter(field_name="shop_price", lookup_expr='lte', label='最大商品价格')
top_category = r_filters.NumberFilter(method='top_category_filter')
def top_category_filter(self, queryset, name, value):
return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) |
Q(category__parent_category__parent_category_id=value))
class Meta:
model = Goods
fields = ['min_price', 'max_price']
DRF的分页功能
全局配置
#settings.py 全局配置
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 10
}
#response style
HTTP 200 OK
{
"count": 1023
"next": "https://api.example.org/accounts/?page=5",
"previous": "https://api.example.org/accounts/?page=3",
"results": [
…
]
}
局部配置
class GoodsPagination(PageNumberPagination):
"""
自定义分页类型
"""
page_size = 10
max_page_size = 100
page_size_query_param = 'page_size'
class CategoryListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
"""
商品类别列表页
"""
queryset = GoodsCategory.objects.filter(category_type=1)
serializer_class = serializers.GoodsCategorySerializer
class CategoryListPaginationViewSet(CategoryListViewSet, GoodsPagination):
"""
集成分页功能的商品类别列表页
"""
pagination_class = GoodsPagination