序列化初试

models

from django.db import models

# Create your models here.
# 新建一个django项目,定义一个Car类,
# 有name字符串属性,
# color整型选择属性(0:银色,1:黑色,2:红色,3:灰色),
# price全精度小数类型,
# image图片文件类型,
# brand字符串类型
class Car(models.Model):
    COLOR_CHOICES = (
        (0,'银色'),
        (1,'黑色'),
        (2,'红色'),
        (3,'灰色'),
    )
    name = models.CharField(max_length=64,verbose_name='车名')
    color= models.IntegerField(choices=COLOR_CHOICES,default=0,verbose_name='颜色')
    price = models.DecimalField(max_digits=10,decimal_places=2,verbose_name='价格')
    image = models.FileField(upload_to='img',default='img/default.png',verbose_name='海报')
    brand = models.CharField(max_length=64,verbose_name='品牌')

    @property
    def col(self):
        return self.get_color_display()

    @property
    def icon(self):
        from django.conf import settings
        return '%s%s%s' % (settings.BASE_URL,settings.MEDIA_URL,self.image)

    def __str__(self):
        return self.name

视图类

from rest_framework.views import APIView
from rest_framework.response import Response
from . import models,serializers

class CarsAPIView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            car_obj = models.Car.objects.filter(pk=pk).first()
            if not car_obj:
                return Response({
                    'status': 1,
                    'msg': 'pk error',
                },status=400)
            car_res =serializers.CarModelSerializer(car_obj,many=False)
            return Response({
                'status': 0,
                'msg': 'ok',
                'results': car_res.data
            })
        else:
            car_obj = models.Car.objects.filter().all()
            car_res = serializers.CarModelSerializer(car_obj, many=True)
            return Response({
                'status': 0,
                'msg': 'ok',
                'results': car_res.data
            })

    def post(self, request, *args, **kwargs):
        car_ser = serializers.CarModelSerializer(data=request.data)
        if car_ser.is_valid():
            # 入库
            car_obj = car_ser.save()
            return Response({
                'status': 0,
                'msg': 'ok',
                'results': serializers.CarModelSerializer(car_obj).data
            })
        else:
            return Response({
                'status': 1,
                'msg': car_ser.errors,
            })

序列化

from rest_framework import serializers
from django.conf import settings
from . import models


class CarModelSerializer(serializers.ModelSerializer):
    re_brand = serializers.CharField(max_length=64,write_only=True)
    class Meta:
        model = models.Car
        fields=('name','col','price','icon','brand','re_brand')
        extra_kwargs = {
            'icon': {
                'read_only': True,  # 自定义的序列化字段默认就是read_only,且不能修改,可以省略
            },
        }
    def validate(self, attrs):
        brand = attrs.get('brand')
        re_brand = attrs.pop('re_brand')
        if brand != re_brand:
            raise serializers.ValidationError({'re_brand': '两次输入不一致'})
        return attrs
上一篇:mysql查询语句


下一篇:SystemVerilog 语言部分(二)