美文网首页
Drf 通用mixins + GenericView方式实现ap

Drf 通用mixins + GenericView方式实现ap

作者: 爱修仙的道友 | 来源:发表于2019-04-25 00:50 被阅读0次
    • 学习须知
      drf 内置了几种GenericView,其分别继承了通用mixinsView,方便我们开发使用


      image.png
    • views.py

    from rest_framework import generics
    
    from . import models
    from .serializers import GoodsSerializer
    
    
    class GoodsList(generics.ListCreateAPIView):
    
        """
        List all goods, or create a new good.
        """
    
        queryset = models.Goods.objects.all()
        serializer_class = GoodsSerializer
    
    
    class GoodsDetail(generics.RetrieveUpdateDestroyAPIView):
        """
        List one good, update the good or delete the good.
        """
    
        queryset = models.Goods.objects.all()
        serializer_class = GoodsSerializer
    
    
    • serializers.py
    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__"
    
    • urls.py
    from . import views
    from django.urls import path
    from rest_framework.urlpatterns import format_suffix_patterns
    
    urlpatterns = [
        path('goods/',views.GoodsList.as_view(),name='goods_list'),
        path('goods/<int:pk>/', views.GoodsDetail.as_view()),
    ]
    
    urlpatterns = format_suffix_patterns(urlpatterns)
    
    • 展示


      image.png
      image.png

    相关文章

      网友评论

          本文标题:Drf 通用mixins + GenericView方式实现ap

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