首页 > 其他分享 >django rest

django rest

时间:2023-01-11 20:34:04浏览次数:59  
标签:serializers rest django instance import data class

djangorest框架是今天看的一个文档。
比较简单的是入门篇,
https://github.com/moocstudent/django-proj
这个呢就是根据入门篇来的代码,
其中比django原教程多的就是关于深入的rest框架的关键点使用。

from django.shortcuts import render

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer

# Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets.
class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]

比如下面这里的ModelViewSet就是一个通用的restful接口组件,

from django.contrib.auth.models import User, Group
from rest_framework import serializers

# Notice that we're using hyperlinked relations in this case with HyperlinkedModelSerializer.
# You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    # meta data set
    class Meta:
        model = User
        # custom fields
        fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']

再比如serializer序列化,这个序列化类在view层进行了指定。
最后接口的路由是通过urls配置的:

from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

整理也就是说前端请求过来之后通过urls找到相应接口路由,
再找到视图views,然后处理相关逻辑,而serializer类似一个处理单元。
在serializer中,原本配置比较多

from rest_framework import serializers
import snippets.models


class SnippetSerializer(serializers.ModelSerializer):
    # id = serializers.IntegerField(read_only=True)
    # title = serializers.CharField(required=False, allow_blank=True, max_length=100)
    # code = serializers.CharField(style={'base_template': 'textarea.html'})
    # linenos = serializers.BooleanField(required=False)
    # language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
    # style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')

    class Meta:
        model = Snippet
        fields = ['id','title','code','linenos','language','style']

   #  def create(self, validated_data):
   #      """
   #      Create and return a new `Snippet` instance, given the validated data.
   #      """
   #      return Snippet.objects.create(**validated_data)
   #
   #  def update(self, instance, validated_data):
   #      """
   #      Update and return an existing `Snippet` instance, given the validated data.
   #      """
   #      instance.title = validated_data.get('title', instance.title)
   #      instance.code = validated_data.get('code', instance.code)
   #      instance.linenos = validated_data.get('linenos', instance.linenos)
   #      instance.language = validated_data.get('language', instance.language)
   #      instance.style = validated_data.get('style', instance.style)
   #      instance.save()
   #      return instance

如果上面第一行是class SnippetSerializer(serializers.Serializer)的话对应注释代码也是
配合serializers.Serializer的,而ModelSerializer则提供了通用的方法。

标签:serializers,rest,django,instance,import,data,class
From: https://www.cnblogs.com/ukzq/p/17044828.html

相关文章

  • [JAVA]RestHighLevelClient的超时设置
    背景设置RestHighLevelClient的超时间,防止请求时间过长,导致接口访问时间过长es官方设置TimeoutsConfiguringrequeststimeoutscanbedonebyprovidinganinstance......
  • django请求日志中间件
    importloggingimporttimefromdjango.httpimportFileResponsefromdjango.utils.deprecationimportMiddlewareMixinaccess_logger=logging.getLogger("acces......
  • Django过滤器、自定义过滤器与自定义标签
    过滤器视图模板过滤器符号为| {{sex|default:"未知"}}--当sex的值为空时,取“未知”{{age|add:"5"}}--给age的值加5{{hobby|fi......
  • Django条件查询When、Case
    目录Django条件查询When、Case1、model和数据准备2、When和Case操作新增字段返回3、条件搜索4、条件更新5、条件聚合Django条件查询When、Case这一篇笔记将介绍条件......
  • Django序列化器的简单使用
    [Django序列化器的简单使用-SSgeek-博客园](https://www.cnblogs.com/ssgeek/p/13263810.html)注意:serializer 不是只能为数据库模型类定义,也可以为非数据库模型类的......
  • Django入门
    入门首先是注意这个发音:D是不发音的,jangoDjango是使用Python语言编写的一个广受欢迎且功能完整的服务器端网站框架。可以方便创建一个基本可用,安全,可扩展,可维护的项......
  • 1011.Django状态保持以及表单
    一、session保持状态状态保持:1.http协议是无状态的:每次请求都是一次新的请求,不会记得之前通信的状态;2.客户端与服务器端的一次通信,就是一次会话实现状态保持的方式:在......
  • SAP restful 接口
    T-CODE:SICF路径:/default_host/sap/bc/rest 右键创建新的子元素登录数据可配、处理器清单为新建类(后续附代码)示例新建类:ZCL_FI4_GET_XXX1METHODif_http_e......
  • Django模板继承与代码块引用(extends/include)
    extends有些页面只有某一部分有变化,其它部分不变时,用模板继承就会比较方便设计母版用{%blockname%}{%endblock%}来代替子模板中需要自己编写的部......
  • client-go 在集群外或集群内加载rest.Config
    在client-go使用时,我们既想要程序在集群内部能够运行,也需要能够在集群外部运行,在集群内部运行能够读取serveraccount信息,在集群外部运行时读取~/.kube/config配置,可以使用......