drf --- 序列化实操

Posted whkzm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了drf --- 序列化实操相关的知识,希望对你有一定的参考价值。

1、整理今天所学知识点

2、新建一个django项目,定义一个Car类,有name字符串属性,color整型选择属性(0:银色,1:黑色,2:红色,3:灰色),price全精度小数类型,image图片文件类型,brand字符串类型

3、基于ModelSerializer类,完成Car资源的单查,群查,单增接口
序列化:显示车名,车的颜色,车的价格,车的海报,车的品牌
反序列化:必须提供车名,车的价格,车的品牌(车的匹配需要二次确认re_brand),车的颜色默认为银色(可以提供),车的海报不需要提供(默认为空)

# serializers.py
from rest_framework import exceptions,serializers
from django.conf import settings
from api import models

class CarSerializer(serializers.Serializer):
    name = serializers.CharField()
    price = serializers.DecimalField(max_digits=8,decimal_places=2)
    brand = serializers.CharField()

    color = serializers.SerializerMethodField()
    def get_color(self,obj):
        return obj.get_color_display()

    img = serializers.SerializerMethodField()
    def get_img(self,obj):
        return f"http://127.0.0.1:8000{settings.MEDIA_URL}{str(obj.image)}"



class CarDeSerializer(serializers.Serializer):
    name = serializers.CharField()
    color = serializers.IntegerField(required=False)
    price = serializers.DecimalField(max_digits=8, decimal_places=2,required=True)
    img = serializers.ImageField(required=False)
    brand = serializers.CharField(required=True)
    re_brand = serializers.CharField(required=True)

    def validate(self, attrs):
        brand = attrs.get('brand')
        re_brand = attrs.pop('re_brand')
        if brand != re_brand:
            raise exceptions.ValidationError('两次品牌不一致')
        return attrs

    def create(self, validated_data):
        return models.Car.objects.create(**validated_data)
# views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models,serializers


class Car(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            car_obj = models.Car.objects.get(pk=pk)
            car_ser = serializers.CarSerializer(car_obj)
            return Response({
                'status':0,
                'msg':'ok',
                'results':car_ser.data
            })
        car_query = models.Car.objects.all()
        car_list_ser = serializers.CarSerializer(car_query,many=True)
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': car_list_ser.data
        })

    def post(self, request, *args, **kwargs):
        if not isinstance(request.data, dict) or request.data == {}:
            return Response({
                'status': 0,
                'msg': '数据异常',
            })

        car_obj = serializers.CarDeSerializer(data=request.data)
        print(car_obj)
        if car_obj.is_valid():
            return Response({
                'status': 0,
                'msg':'ok',
                'results':serializers.CarSerializer(car_obj).data
            })
        else:
            return Response({
                'status': 0,
                'msg': 'ok',
                'results':car_obj.errors
            })
# api.urls.py
from django.conf.urls import url,include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/',include('api.urls')),
    url(r'^media/(?P<path>.*)',serve,{"document_root":settings.MEDIA_ROOT})

]

以上是关于drf --- 序列化实操的主要内容,如果未能解决你的问题,请参考以下文章

DRF序列化代码

#私藏项目实操分享#愚公系列2022年05月 Python教学课程 75-DRF框架之排序

DRF视图

DRF视图

DRF视图 𵀝

drf框架 2 drf框架的请求生命周期(as_view和dispatch方法), 请求解析渲染响应异常, 序列化组件 ,ORM配置回顾(media文件配置),应用在settings.py中(代码片