码迷,mamicode.com
首页 > 其他好文 > 详细

django的serializers

时间:2018-06-01 00:19:35      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:ida   patch   ted   ima   url   app   直接   self   require   

views.py

# get所需的
from snippets.serializers import SnippetSerializer
from rest_framework.views import APIView
from rest_framework.response import Response # 是drf的response

# post所需的
from snippets.models import Snippet
from django.http import Http404
from rest_framework import status


class SnippetList(APIView):
    """
    这是SnippetList接口的一些描述信息
    List all snippets, or create a new snippet.
    """

    def get(self, request, format=None):
        """获取"""
        snippets = Snippet.objects.all()
        snippets_serializer = SnippetSerializer(snippets, many=True)
        return Response(snippets_serializer.data)

    def post(self, request, format=None):
        serializer = SnippetSerializer(data=request.data) # drf的request,可以直接取出用户过来的body数据 / post数据
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

#!/usr/bin/env python
# coding=utf-8

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES


class SnippetSerializer(serializers.Serializer):

    id = serializers.IntegerField(read_only=True) # read_only先不管
    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')

    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

snippets/urls.py

from django.urls import path, include
from django.conf.urls import url
from snippets import views

app_name = 'snippets'
urlpatterns = [
    # path('', views.index, name="index"),
    path('snippets', views.SnippetList.as_view(), name="snippets"),
]

urls.py

from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url

urlpatterns = [
    path('app01/', include("app01.urls")),
    path('app02/', include("app02.urls")),
    path('app03/', include("app03.urls")),
    path('app04/', include("app04.urls")),
    path('app05/', include("app05.urls")),
    path('app06/', include("app06.urls")),
    path('app07/', include("app07.urls")),
    path('app08/', include("app08.urls")),
    path('snippets/', include("snippets.urls")),
    path('admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

技术分享图片

添加数据

[
  {
    "id": 1,
    "title": "",
    "code": "foo = \"bar\"\n",
    "linenos": false,
    "language": "python",
    "style": "friendly"
  },
  {
    "id": 2,
    "title": "",
    "code": "print \"hello, world\"\n",
    "linenos": false,
    "language": "python",
    "style": "friendly"
  }
]

技术分享图片

http://www.django-rest-framework.org/tutorial/1-serialization/#using-modelserializers
技术分享图片

# 使用ModelSerializer,类似modelform, http://www.django-rest-framework.org/tutorial/1-serialization/#using-modelserializers
class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        # fields ="__all__"
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

技术分享图片

嵌套
技术分享图片

技术分享图片
技术分享图片

优化listview: http://www.django-rest-framework.org/tutorial/3-class-based-views/
技术分享图片

技术分享图片

技术分享图片

技术分享图片

ListAPIView                     get
RetrieveAPIView                 get
DestroyAPIView                  delete
UpdateAPIView                   update
ListCreateAPIView               get/post
RetrieveUpdateAPIView           get/put/patch
RetrieveDestroyAPIView          get/delete
RetrieveUpdateDestroyAPIView    get/put/patch/delete

分页
技术分享图片
技术分享图片

技术分享图片

django的serializers

标签:ida   patch   ted   ima   url   app   直接   self   require   

原文地址:https://www.cnblogs.com/iiiiiher/p/9119679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!