序列化(一)

序列化的作用

  • 用来序列化数据。ORM->JSON
  • 用来验证表单数据。Form
  • 可以创建数据,修改数据等。

Serializer的构造函数的参数:

  • instance:需要传递一个ORM对象,或者是一个queryset对象。用来将ORM模型序列化成JSON的
  • data:把需要验证的数据传给data,用来验证这些数据是不是符合要求。
  • many:如果instance是一个queryset对象,那么就需要设置为True,否则为False

自定义验证、创建、修改数据

  • 复写update、create方法。要在update方法中使用instance.save()进行保存。
  • 通过重写validate(self,attrs)方法进行验证。attrs中包含了所有字段。如果验证不通过,那么调用raise serializer.ValidationError('error')即可。
  • 当只针对单个字段验证时可以定义def validate_要验证字段的名(self,value)方法
class MerchantSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=200,required=True,error_messages={"required":"name必须要传!"})
    logo = serializers.CharField(max_length=200,required=True)
    address = serializers.CharField(max_length=200,required=True)
    notice = serializers.CharField(max_length=200,required=False)
    up_send = serializers.DecimalField(required=False,max_digits=6,decimal_places=2)
    lon = serializers.FloatField(required=True)
    lat = serializers.FloatField(required=True)

    def validate(self,attrs):
        raise serializer.ValidationError('验证失败')

    def validate_name(self,value):
        raise serializer.ValidationError('验证失败')

    def update(self, instance, validated_data):
        instance.name = validated_data.get('name',instance.name)
        instance.logo = validated_data.get('logo', instance.logo)
        instance.address = validated_data.get('address', instance.address)
        instance.notice = validated_data.get('notice',instance.notice)
        instance.up_send = validated_data.get('up_send', instance.up_send)
        instance.lon = validated_data.get('lon', instance.lon)
        instance.lat = validated_data.get('lat', instance.lat)
        instance.save()
        return instance

    def create(self, validated_data):
        return Merchant.objects.create(**validated_data)
from .serializers import MerchantSerializer,GoodsCategorySerializer
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from meituan.models import Merchant,GoodsCategory,Goods
from rest_framework.response import Response

@require_http_methods(['GET','POST'])
def merchant(request):
    # get:返回所有的商家
    # post:创建新的商家
    if request.method == 'GET':
        queryset = Merchant.objects.all()
        serializer = MerchantSerializer(instance=queryset,many=True)
        return JsonResponse(serializer.data,status=200,safe=False)
    else:
        serializer = MerchantSerializer(data=request.POST)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=200)
        else:
            return JsonResponse(serializer.errors, status=400)

def category(request):
    if request.method == 'GET':
        queryset = GoodsCategory.objects.all()
        serializer = GoodsCategorySerializer(instance=queryset,many=True)
        return JsonResponse(serializer.data,safe=False)
    else:
        serializer = GoodsCategorySerializer(data=request.POST)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data,status=200)
        else:
            return JsonResponse(serializer.errors, status=400)


posted @ 2020-12-26 16:04  xsan  阅读(101)  评论(0编辑  收藏  举报