drf-序列化和反序列化。---查询和提交 之Serializer

https://www.bilibili.com/video/BV1z5411D7BQ?p=8&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea

https://www.bilibili.com/video/BV1z5411D7BQ?p=9&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea

 

models.py

from django.db import models

# Create your models here.
class Book(models.Model):
    title=models.CharField(max_length=55,verbose_name="书籍名称")
    price=models.IntegerField(verbose_name="价格")
    # pub_date=models.DateField(verbose_name="出版日期")
    pub_date = models.CharField(max_length=55,verbose_name="出版日期")
    sex=models.CharField(
        max_length=55,
        #设置提交的时候该字段只能提交1 或者 0 ,不然接口会提示错误 {"sex": ["\"3\" is not a valid choice."]}
        choices=((1,"man"),(0,"woman")),
        verbose_name="性别")

 

views.py

注意:

序列化模型传instance为序列化

序列化模型传data为反序列化

from django.shortcuts import render

# Create your views here.


from rest_framework.views import APIView
from sers.models import  Book
from rest_framework import serializers
from rest_framework.response import Response


# 针对模型设计序列化器 ----查询数据库数据赋值到这个类然后扔出去
# (我把数据转成json给前端发叫序列化)
class BookSerializers(serializers.Serializer):
    id=serializers.IntegerField(read_only=True)#在客户端提交数据【反序列化阶段不会要求有id字段】 可以不传 传了也不会反序列化进来..  (可传空为null 不传)required=False,allow_null=True,allow_blank=True
    title = serializers.CharField(max_length=8)
    price = serializers.IntegerField(required=False)  #required=True=反序列化阶段非必填)
    # 左边date是给出去的字段,右边soure是具体数据模型对应取值的字段
    date = serializers.CharField(source="pub_date")

    # 接口输出例子
    # [
    #     {
    #         "id": 1,
    #         "title": "aabook",
    #         "price": 199,
    #         "date": "2020-12-12 00:00:00"
    #     }]


class BookView(APIView):
    def get(self,request):
        # 获取所有书籍
        book_list=Book.objects.all()
        #这步其实就是把把查出来的数据赋值到序列化模型里---单条数据不需要many属性
        serializer = BookSerializers(instance=book_list, many=True)
        '''
        上面实现的大概逻辑
        temp=[]
        for obj in book_list:
            d ={}
            d["title"]= obj.title
            d["date"]= obj.pub_date
            trmp.append(d)
        '''
        # # # # 调用序列化对象的data获取序列化后的数据
        data = serializer.data
        return Response(data)


    def post(self,request):
        # 获取请求的数据 #request.data可以拿到表单或json的数据
        print("data",request.data)
        # 构建序列化器
        serializer = BookSerializers(data=request.data)
        # # 校验数据--返回boolen值,成功信息放到serializer.validated_data,错误信息放到serializer.errors
        if serializer.is_valid():
            # 数据插入到数据库中
            # 直接数据模型可插入
            Book.objects.create(**serializer.validated_data)
            #这种写法也可以插入数据
            # Book.objects.create(title="111")
            #数据校验通过
            return Response(f'校验成功信息:{serializer.validated_data}') #serializer.validated_data是反序列化成数据模型了
            # return Response(f'校验成功信息:{serializer.data}') #"校验成功信息:{'title': 'j11', 'price': 1999, 'date': '2020-12-12 00:00:00'}"
        else:
            # 数据校验失败
            return Response(f'校验失败信息:{serializer.errors}')

 

序列化的属性 https://www.cnblogs.com/lifei01/p/13381386.html#T3

其他序列化事可以加的属性  https://blog.csdn.net/adminwg/article/details/126610747

 

追加字段校验  extra_kwargs 

 class Meta:
        model = tbl_group_case
        fields = ('id', 'groupname', 'status_case', 'project_id', 'environment')
        extra_kwargs = {
            'groupname': {
                'required': True,
                'min_length': 4,
                'max_length': 12,
                'error_messages': {
                    'required': '字段必填',
                    'min_length': '字段太短',
                    'max_length': '字段太长',
                }
            },
            'status_case': {
                'read_only': True,
            },
            'id': {
                'read_only': True,
            },
        }

model

class tbl_group_case(models.Model):
    STATUS_NORMAL = 0
    STATUS_FLIA = 1
    STATUS_RUN = 2
    STATUS_DEFAULT = 3
    STATUS_ITEMS = (
        (STATUS_NORMAL, '通过'),
        (STATUS_FLIA, '失败'),
        (STATUS_RUN, '运行中'),
        (STATUS_DEFAULT, '未运行'),
    )
    environment = models.CharField(max_length=20, verbose_name='运行环境', default='test')
    groupname = models.CharField(max_length=20, verbose_name='业务流程名')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    status_case = models.PositiveIntegerField(default=STATUS_DEFAULT,
                                              choices=STATUS_ITEMS,
                                              verbose_name='业务状态')
    project_id = models.IntegerField()
    is_deleted = models.BooleanField(default=False, null=False)

    class Meta:
        db_table = 'tbl_group_case'

 

posted @ 2022-10-18 14:32  凯宾斯基  阅读(73)  评论(0编辑  收藏  举报