-
学习须知
image.png - 序列化器
from rest_framework import serializers
from . import models
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = models.GoodsCategory
fields = "__all__"
class GoodsSerializer(serializers.ModelSerializer):
# 重写外键,序列化输出
category = CategorySerializer()
class Meta:
model = models.Goods
fields = "__all__"
- Viewset 视图
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from . import models
from .serializers import GoodsSerializer
class GoodsPagination(PageNumberPagination):
page_size = 2
max_page_size = 100
# 自动返回第n页
page_query_param = "p"
# 自动返回n页
page_size_query_param = 'page_size'
class GoodsList(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
# queryset = models.Goods.objects.get_queryset()
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
def get_queryset(self):
return models.Goods.objects.get_queryset().filter(market_price__gt=50)
- app路由
from . import views
from rest_framework.routers import DefaultRouter
urlpatterns = [
]
router = DefaultRouter()
# 这个basename 很重要 ,`basename`参数未指定,并且无法自动确定视图集中的名称,因为它没有`.queryset`属性。
router.register(r'goods',views.GoodsList,basename='good')
urlpatterns += router.urls
-
展示
image.png
网友评论