温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何正确的使用Restful_framework视图组件

发布时间:2020-11-18 14:36:23 来源:亿速云 阅读:150 作者:Leah 栏目:开发技术

这篇文章给大家介绍如何正确的使用Restful_framework视图组件,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

一、基本视图

写一个出版社的增删查改resful接口

要自己事先创建好django项目,并创建好表,添加完记录

路由:

url(r'^publish/$', views.PublishView.as_view()),
url(r'^publish/(&#63;P<pk>\d+)/$', views.PublishDetailView.as_view()),

视图:

from api import modelsfrom rest_framework import serializersfrom rest_framework.response import Responsefrom rest_framework.views import APIView
class PublishSerializers(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'

class PublishView(APIView):
  #查询出版社表中所有记录
  def get(self, request):
    publish_list = models.Publish.objects.all()
    bs = PublishSerializers(publish_list, many=True)
    # 序列化数据

    return Response(bs.data)  #返回的结果是列表中套字典
  
  def post(self, request):
    # 添加一条数据
    print(request.data)

    bs=PublishSerializers(data=request.data)
    if bs.is_valid():
      bs.save() # 生成记录
      return Response(bs.data)  #返回的是添加成功记录的字典
    else:

      return Response(bs.errors)

class PublishDetailView(APIView):   #查询某一条数据
  def get(self,request,pk):
    publish_obj=models.Publish.objects.filter(pk=pk).first()
    bs=PublishSerializers(publish_obj,many=False)
    return Response(bs.data)   #更新某一条数据
  def put(self,request,pk):
    publish_obj = models.Publish.objects.filter(pk=pk).first()

    bs=PublishSerializers(data=request.data,instance=publish_obj)
    if bs.is_valid():
      bs.save() # update
      return Response(bs.data)
    else:
      return Response(bs.errors)   #删除某一条数据
  def delete(self,request,pk):
    models.Publish.objects.filter(pk=pk).delete()

    return Response("")

二、mixins类和generic类编写视图

路由:

url(r'^publishes$', views.Publish.as_view()),
url(r'^publish/(&#63;P<pk>\d+)', views.PublishDetail.as_view()),

视图:

from api import models
from rest_framework import serializers
from rest_framework import mixins
from rest_framework.generics import GenericAPIView
class PublishSer(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'
class Publish(GenericAPIView,mixins.ListModelMixin,mixins.CreateModelMixin):
  queryset = models.Publish.objects.all()
  serializer_class = PublishSer
  def get(self,request):
    return self.list(request)  #在ListModelMixin下有一个list方法,返回的就是查询的结果:Response(serializer.data)
  def post(self,request):
    return self.create(request) #已经封装好了,帮我们做校验和序列化,返回的是添加成功的记录
class PublishDetail(GenericAPIView,mixins.DestroyModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin):

  queryset = models.Publish.objects.all()
  serializer_class = PublishSer
  def get(self,request,*args, **kwargs):
    return self.retrieve(request,*args, **kwargs)

  def put(self,request,*args, **kwargs):
    return self.update(request,*args, **kwargs)

  def delete(self,request,*args, **kwargs):
    return self.destroy(request,*args, **kwargs)

三、使用generic下ListCreateAPIView和RetrieveUpdateDestroyAPIView

路由:

url(r'^publishes$', views.Publish.as_view()),
url(r'^publish/(&#63;P<pk>\d+)', views.PublishDetail.as_view()),

视图:

from api import models
from rest_framework import mixins
from rest_framework.generics import GenericAPIView
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
from rest_framework import serializers
class Publishser(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'

class Publish(ListCreateAPIView):
  queryset = models.Publish.objects.all()
  serializer_class = Publishser

class PublishDetail(RetrieveUpdateDestroyAPIView):
  queryset = models.Publish.objects.all()
  serializer_class = Publishser

四、使用ModelViewSet

路由:

url(r'^publish$',views.Publish.as_view({'get':'list','post':'create'})),
url(r'^publish/(&#63;P<pk>\d+)', views.Publish.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),

视图:

from rest_framework.viewsets import ModelViewSet
from api import models
from rest_framework import serializers
class Publishser(serializers.ModelSerializer):
  class Meta:
    model=models.Publish
    fields='__all__'
class Publish(ModelViewSet):
  queryset = models.Publish.objects.all()
  serializer_class = Publishser

关于如何正确的使用Restful_framework视图组件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI