django的serializers

本文介绍如何使用Django Rest Framework(DRF)进行序列化操作,并实现基本的CRUD功能。通过SnippetList视图展示如何获取所有代码片段或创建新的代码片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

1312420-20180531233559651-24019741.png

添加数据

[
  {
    "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"
  }
]

1312420-20180531233531046-1192991881.png

http://www.django-rest-framework.org/tutorial/1-serialization/#using-modelserializers
1312420-20180531234135629-1308776779.png

# 使用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')

1312420-20180531234206810-1631157787.png

嵌套
1312420-20180531234319264-1890256494.png

1312420-20180531234335364-385026376.png
1312420-20180531234359586-1728719365.png

优化listview: http://www.django-rest-framework.org/tutorial/3-class-based-views/
1312420-20180531234458990-250501929.png

1312420-20180531234924573-2110652104.png

1312420-20180531234909699-919040682.png

1312420-20180531235546539-436622935.png

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

分页
1312420-20180531235713970-1684881928.png
1312420-20180531235725874-2106078970.png

1312420-20180531235741976-1966802052.png

1312420-20180601001012342-596493018.png
1312420-20180601001024604-1609869975.png

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 1
}

使用api
1312420-20180601001213268-1501234527.png
1312420-20180601001418026-1427265557.png

转载于:https://www.cnblogs.com/iiiiiher/p/9119679.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值