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'})),

转载于:https://www.cnblogs.com/jianhaozhou/p/10132326.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值