zoukankan      html  css  js  c++  java
  • 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'})),
    
  • 相关阅读:
    redis 写入数据 越来越慢 是什么原因
    redis slowlog
    JavaCC 规格严格
    Lucene 规格严格
    数据库建立索引要点 规格严格
    编辑距离 规格严格
    Lucene NRT (Near Real Time) 规格严格
    事件关联 规格严格
    linux下mysql5.5.19编译安装笔记【已验证】 规格严格
    关于CLOSE BY CLIENT STACK TRACE 规格严格
  • 原文地址:https://www.cnblogs.com/jianhaozhou/p/10132326.html
Copyright © 2011-2022 走看看