drf部分

Posted luguochang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了drf部分相关的知识,希望对你有一定的参考价值。

Django 1.11.3

Serializers.py

from rest_framework import serializers
from .models import Goods,GoodsCategory

class GoodCategorySerializer(serializers.ModelSeliazer):
  class Meta:
    models=GoodCategory
    field="__all__" //field=["id","name"]
    
class GoodsSerializer(serializers.ModelSerializer):
  category=GoodCategorySeriazlize() //(many=True),部分重定义,会显示详细内容
  class Meta:
    models=Goods
    field="__all__"



views
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.viewsets import mixins

GenericViewset(Viewset)  -drf
  GenericAPIView  -drf
    APIView  -drf
      View  -django

 


mixin
  1.listModelMixin
    //帮助做过滤、分页、序列化
  
  2.createModelMixin
    //创建视图扩展类,提供create(request, *args, **kwargs)方法快速实现创建资源的视图,成功返回201状态码。
class CreateModelMixin(object):
    """
    Create a model instance.
    """
    def create(self, request, *args, **kwargs):
        # 获取序列化器
        serializer = self.get_serializer(data=request.data)
        # 验证
        serializer.is_valid(raise_exception=True)
        # 保存
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
 
    def perform_create(self, serializer):
        serializer.save()
 
    def get_success_headers(self, data):
        try:
            return {Location: str(data[api_settings.URL_FIELD_NAME])}
        except (TypeError, KeyError):
            return {}
————————————————
  
  3.updateModelMixin
  4.destroyModelMixin
  5.retrieveModelMixin
  6.各种组合
url.py
from rest_framework import DefaultRouter

router=DefaultRouter()
router.register(rgoods,GoodListViewset,base_name="goods")  //配置Goods的url
router.register(.....)
urlpatterns=[
  url(r^,include(router.urls)),

]

eg:
  1.
  APIView - ModelSerialzer
  url(r^news/agree/$,article.NewAgreeView.as_view())
  url(r^news/collect/(?P<pk>d+)/$,article.Collect.as_view())
  class NewAgreeView(APIView)
    def post(self,request,*args,**kwargs):
      ....
    class NewAgreeView(APIView)
    def post(self,request,*args,**kwargs):
      nid=kwargs.get("pk")
  
  2.
  url(r^news/$,article.Article.as_view({get:list})),
  url(r^news/(?P<pk>/d+)/$,article.Article.as_view({get:retrieve}))
    
   class ArticleView(ViewSetMixin, APIView):
    def list(self,request,*args,**kwargs):
      ...
    def retrieve(self,request,*args,**kwargs):
      ...

 

  

    

以上是关于drf部分的主要内容,如果未能解决你的问题,请参考以下文章

06 drf源码剖析之权限

DRF部分源码简介及序列化组件

drf序列化器之请求响应以及视图

argparse 代码片段只打印部分日志

067.Python框架Django之DRF视图类

部分代码片段