码迷,mamicode.com
首页 > 其他好文 > 详细

Django REST framework 构建通用模型

时间:2020-10-29 10:11:13      阅读:18      评论:0      收藏:0      [点我收藏+]

标签:ima   user   pat   framework   大神   objects   des   post   ica   

  在使用drf过程中,发现要写大量的serializers、view,在借鉴了各位大神的经验后,简化一下代码

#base/view.py:通用部分

from rest_framework.views import APIView
from rest_framework.response import Response

class GenericAPIView(APIView):
    queryset = None
    serializer_class = None

    def get(self, request, id=None):
        return self.retrieve(request, id)

    def patch(self, request, id=None):
        return self.update(request, id)

    def delete(self, request, id=None):
        return self.destroy(request, id)

    def get_queryset(self):
        return self.queryset.all()

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def retrieve(self, request, id):
        if not id:
            queryset = self.get_queryset()
            ser_obj = self.get_serializer(queryset, many=True)
        else:
            ser_obj = self.get_queryset().filter(id=id).first()
            if not ser_obj:
                return Response({‘code‘:0,‘msg‘:‘数据不存在!‘})
            ser_obj = self.get_serializer(ser_obj)
        return Response({‘code‘:1,‘data‘:ser_obj.data})

    def create(self, request,**kwargs):
        postdata=request.data.copy()#querydict先copy为可变对象
        [postdata.__setitem__(i,kwargs[i]) for i in kwargs]

        ser_obj = self.get_serializer(data=postdata)
        if ser_obj.is_valid():
            ser_obj.save()
            return Response({‘code‘:1,‘msg‘:‘创建成功!‘,‘data‘:ser_obj.data})
        else:
            return Response({‘code‘:0,‘msg‘:‘失败!‘,‘data‘:ser_obj.errors})

    def update(self, request, id):
        ser_obj = self.get_queryset().filter(id=id).first()
        ser_obj = self.get_serializer(instance=ser_obj, data=request.data, partial=True)
        if ser_obj.is_valid():
            ser_obj.save()
            return Response({‘code‘:1,‘msg‘:‘修改成功!‘})
        else:
            return Response({‘code‘:0,‘msg‘:‘提交失败!‘,‘data‘:ser_obj.errors})

    def destroy(self, request, id):
        ser_obj = self.get_queryset().filter(id=id).first()
        if ser_obj:
            ser_obj.delete()
            return Response({‘code‘:1,‘msg‘:‘删除成功!‘})
        else:
            return Response({‘code‘:0,‘msg‘:‘删除失败,对象不存在!‘})

  没有写post写到view里面,设置一些自定义字段

#app/view.py

@method_decorator(csrf_exempt,name=‘post‘)
class projectView(GenericAPIView):
    queryset = project.objects.all()
    serializer_class = ProjectSerializer
    def post(self,request):
        return self.create(request,creater=request.user.id)

  

#serializer.py 按需写就行

class ProjectSerializer(serializers.HyperlinkedModelSerializer):
    id=serializers.IntegerField(read_only=True)
    name=serializers.CharField(required=True,allow_blank=False,max_length=200)
    content=serializers.CharField(max_length=200,required=True,allow_blank=False,)
    img=serializers.URLField(required=False,)
    creater=serializers.PrimaryKeyRelatedField(queryset=member.objects.all(),required=False,allow_null=True )
    # creater=serializers.SerializerMethodField()
    class Meta:
        model=project
        fields=[‘id‘,‘name‘,‘content‘,‘img‘,‘creater‘]

  最后,只需要写serializer和具体业务方法。当然在此基础上还需要扩展,但是已经减少了很多代码了。以后会更新一些扩展示例。

 

Django REST framework 构建通用模型

标签:ima   user   pat   framework   大神   objects   des   post   ica   

原文地址:https://www.cnblogs.com/rainny/p/13892296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!