美文网首页Django
Drf Viewset和router方式实现api接口和url配

Drf Viewset和router方式实现api接口和url配

作者: 爱修仙的道友 | 来源:发表于2019-04-25 02:39 被阅读0次
  • 学习须知


    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
image.png

相关文章

网友评论

    本文标题:Drf Viewset和router方式实现api接口和url配

    本文链接:https://www.haomeiwen.com/subject/ngkogqtx.html