1. 主页
  2. DRF实战教程
  3. DRF实战之序列化

DRF实战之序列化

模型类

创建模型类

from django.db import models
# Create your models here.
class Article(models.Model):
    title = models.CharField(verbose_name='标题', max_length=100)
    vum = models.IntegerField(verbose_name='浏览量')
    content = models.TextField(verbose_name='内容')

序列化

创建序列化文件

from rest_framework import serializers
from .models import Article
​
class ArticleSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    vnum = serializers.IntegerField()
    content = serializers.CharField(max_length=1000)
    title = serializers.CharField(required=True, max_length=100)
​
    def create(self, validated_data):
        return Article.objects.create(**validated_data)
​
    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.vnum = validated_data.get('vnum', instance.vnum)
        instance.content = validated_data.get('content', instance.content)
        instance.save()
        return instance

参数约束

read_only:True表示不允许用户自己上传,只能用于api的输出。
write_only: 与read_only对应
required: 顾名思义,就是这个字段是否必填。
allow_null/allow_blank:是否允许为NULL/空 。
error_messages:出错时,信息提示。
name = serializers.CharField(required=True, min_length=6,
                error_messages={
                    'min_length': '名字不能小于6个字符',
                    'required': '请填写名字'})
label: 字段显示设置,如 label=’验证码’
help_text: 在指定字段增加一些提示文字,这两个字段作用于api页面比较有用
​style: 说明字段的类型,这样看可能比较抽象,看下面例子:
# 在api页面,输入密码就会以*显示
password = serializers.CharField(
    style={'input_type': 'password'})
# 会显示选项框
color_channel = serializers.ChoiceField(
    choices=['red', 'green', 'blue'],
    style={'base_template': 'radio.html'})
validators:自定义验证逻辑

利用序列化生成JSON数据

from rest_framework.renderers import JSONRenderer
art = Article.objects.get(id=1)
ser = ArticleSerializer(art)
json_data = JSONRenderer().render(ser.data)

# 多个对象序列化
art = Article.objects.all()
ser = ArticleSerializer(art,many=True)  #  如果多个对象序列化 需要加many
ser.data

利用反序列化生成模型对象

python manage.py shell
from app03.serializers import ArticleSerializer
d = {"title":"这是一个测试标签","vnum":11,"content":"哈哈哈哈"}
ser = ArticleSerializers(data=d)
ser.is_valid()# 验证数据是否正确
ser.save()# 保存数据

ModelSerializer

ModelSerializers默认帮我们实现了创建和更新方法,简化了我们的操作,当然如果你想自己写,可以重写它。其余使用方法跟普通的序列化一样。

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'title', 'vnum', 'content')       三者取一
        # exclude = () 表示不返回字段        三者取一
        # fields = '__all__': 表示所有字段       三者取一
        # read_only_fields = () #设置只读字段 不接受用户修改

编写视图

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from .models import Article
from .serializers import ArticleSerializer


class JSONResponse(HttpResponse):
 
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)


@csrf_exempt
def article_list(request):
    if request.method == 'GET':
        articles = Article.objects.all()
        serializer = ArticleSerializer(articles, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = ArticleSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)

编写路由

from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path('articles/', views.article_list),  # 获取或创建
]

根级路由

from django.contrib import admin
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app03/', include('app03.urls')),
]

编写删除和更新

@csrf_exempt
def article_detail(request, id):
    try:
        article = Article.objects.get(id=id)
    except Article.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = ArticleSerializer(article)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = ArticleSerializer(article, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        article.delete()
        return HttpResponse(status=204)

编写路由

from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path('articles/', views.article_list),  # 获取或创建
    path('articles/<int:id>', views.article_detail),  # 查找、更新、删除
]

我们要如何帮助您?

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注