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'})),
    
  • 相关阅读:
    Navicat 远程连接ubuntu出现的问题
    替换 ubuntu 自带的python版本
    xpath疑惑
    xpath中返回值问题
    AttributeError: 'unicode' object has no attribute 'xpath'
    linux下mysql忘记密码解决方案
    IntelliJ idea常用快捷键
    最近的说明(本篇不谈具体技术,看技术的可以忽略)
    常用的排序算法介绍和在JAVA的实现(二)
    mysql数据库查询过程探究和优化建议
  • 原文地址:https://www.cnblogs.com/jianhaozhou/p/10132326.html
Copyright © 2011-2022 走看看