DRF视图+路由

DRF视图+路由

1.实现一个视图类满足多趟路由(继承ViewSetMixin)

​ 1)视图类的写法

from rest_framework.viewsets import ModelViewSet,ViewSetMixin
from rest_framework.views import APIView
from app01 import models
from app01 import common
class AuthorView(ViewSetMixin,APIView):
    def get_one_author(self,request,pk):
        author = models.Author.objects.filter(id=pk).first()
        author_res = common.AuthorJson(instance=author,many=False)
        return JsonResponse({'author':author_res.data},safe=False)
    def get_all_author(self,request):
        author = models.Author.objects.all()
        author_res = common.AuthorJson(instance=author,many=True)
        return JsonResponse(author_res.data,safe=False)

​ 2)两趟get路由

url(r'author/$',views.AuthorView.as_view({'get':'get_all_author'})),
url(r'author/(?P<pk>\d+)',views.AuthorView.as_view({'get':'get_one_author'})),

​ 3)序列化函数

​ 方式一:

from rest_framework import serializers
class AuthorJson(serializers.ModelSerializer):
    class Meta:
        model = models.Author
        fields = '__all__'

​ 方式二:

from rest_framework import serializers
class AuthorsDRF(serializers.Serializer):
    author_id = serializers.IntegerField(source='id')
    author_name = serializers.CharField(source='name')
    author_sex = serializers.CharField(source='sex')
    addr = serializers.CharField()

2.使用DRF提供的视图(可以完成对数据库的增删改查)

​ 1)视图函数的写法

from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
    queryset = models.Publish.objects.all()
    serializer_class = common.PublishSerializers

​ 2)路由的写法

url(r'publish/$',views.PublishView.as_view({'get':'list','post':'create'})),

url(r'publish/(?P<pk>\d+)',views.PublishView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
posted @ 2018-12-17 16:39  周建豪  阅读(174)  评论(0编辑  收藏  举报