• Django REST Framework序列化


    一、自定义序列化

    1、url

    urlpatterns = [
        path('books/', books, name='books')
    ]

    2、model

    class Book(models.Model):
        b_name = models.CharField(max_length=20)
        b_price = models.FloatField(default=1)
    
        def to_dict(self):
            return {
                'b_name': self.b_name,
                'b_price': self.b_price
            }

    3、视图

    @csrf_exempt
    def books(request):
        if request.method == 'GET':
            book_list = Book.objects.all()
            book_list_json = []
            for book in book_list:
                book_list_json.append(book.to_dict())
                print(book_list_json)
    
            data = {
                'status': 200,
                'msg': 'ok',
                'data': book_list_json
            }
    
            return JsonResponse(data=data)
    
        elif request.method == 'POST':
            b_name = request.POST.get('b_name')
            b_price = request.POST.get('b_price')
    
            book = Book()
            book.b_name = b_name
            book.b_price = b_price
            book.save()
    
            data = {
                'status': 201,
                'msg': 'ok',
                'data': book.to_dict()
            }
    
            return JsonResponse(data=data, status=201)

     二、Django REST Framework序列化

    1、小试牛刀

    (1)、model

    class Person(models.Model):
        p_name = models.CharField(max_length=32)
        p_age = models.IntegerField(default=1)
        p_sex = models.BooleanField(default=False)

    (2)、序列化类

    创建一个serializers.py文件

    from rest_framework import serializers
    
    from Api.models import Person
    
    
    class PersonSerializer(serializers.Serializer):
    
        id = serializers.IntegerField(read_only=True)
        p_name = serializers.CharField(max_length=32)
        p_age = serializers.IntegerField(default=1)
        p_sex = serializers.BooleanField(default=False)
    
        def create(self, validated_data):
            return Person.objects.create(**validated_data)
    
        def update(self, instance, validated_data):
    
            instance.p_name = validated_data.get('p_name', instance.p_name)
            instance.p_age = validated_data.get('p_age', instance.p_age)
            instance.p_sex = validated_data.get('p_sex', instance.p_sex)
            instance.save()
    
            return instance

    序列化器类的第一部分定义了序列化/反序列化的字段。create()update()方法定义了在调用serializer.save()时如何创建和修改完整的实例。

    序列化器类与Django Form类非常相似,并在各种字段中包含类似的验证标志,例如requiredmax_lengthdefault

    (3)、视图

    class PersonView(View):
    
        def get(self, request):
    
            persons = Person.objects.all()
    
            person_serializer = PersonSerializer(persons, many=True)
    
            return JsonResponse(person_serializer.data, safe=False)
    
        def post(self, request):
    
            p_name = request.POST.get("p_name")
            p_age = request.POST.get("p_age")
    
            person = Person()
    
            person.p_name = p_name
    
            person.p_age = p_age
    
            person.save()
    
            person_serializer = PersonSerializer(person)
    
            return JsonResponse(person_serializer.data)

     

     2、使用ModelSerializers

    我们的PersonSerializer类中重复了很多包含在Person模型类(model)中的信息。如果能保证我们的代码整洁,那就更好了.

    就像Django提供了Form类和ModelForm类一样,REST framework包括Serializer类和ModelSerializer类。

    注意:

        下面的request已经不是django中的renquest,而是rest framework中的。

        在post请求中可以直接使用request.data获取到所有数据进行序列化。

    request.data  # 处理任意数据  适用于'POST','PUT'和'PATCH'方法

    (1)、序列化

    class PersonSerializer(serializers.ModelSerializer):
        class Meta:
            model = Person
            #fields = ('id', 'p_name', 'p_age', 'p_sex')
         fields = "__all__"

    (2)、视图

    class PersonView(APIView):
        def get(self, request):
            persons = Person.objects.all()
            person_serializer = PersonSerializer(persons, many=True)   # 使用序列化类进行序列化
            return Response(person_serializer.data)
    
        def post(self, request):
            # p_name = request.POST.get('p_name')
            # p_age = request.POST.get('p_age')
            # person = Person()
            # person.p_name = p_name
            # person.p_age = p_age
            # person.save()
            person_serializer = PersonSerializer(data=request.data)
            if person_serializer.is_valid():  # 验证数据合法性
                person_serializer.save()
                return Response(person_serializer.data)
            return Response(data={'msg': 'error'}, status=status.HTTP_400_BAD_REQUEST)

    3、序列化常规Django视图函数

    @csrf_exempt
    @api_view(http_method_names=['GET', 'POST'])
    def persons(request):
    print(type(request))
    if request.method == 'GET':
    person = Person.objects.all()
    person_serializer = PersonSerializer(person, many=True)
    print(person_serializer)
    return Response(person_serializer.data)


    elif request.method == 'POST':
    person_serializer = PersonSerializer(data=request.data)
    if person_serializer.is_valid():
    person_serializer.save()
    return Response(person_serializer.data)
    return Response(data={'msg': 'error'}, status=status.HTTP_400_BAD_REQUEST)

     

    
    
    
  • 相关阅读:
    Python进阶开发之元类编程
    django相关网站
    Ubuntu下vim中文乱码
    django自定义用户表
    C# webbrowser遍历网页元素
    Delphi SetParent 嵌入其他应用程序
    C# DataGirdview手动添加数据,导出txt文件并自动对齐
    C# SetParent将其他程序嵌入自己的程序
    Delphi如何找到出错行的行数!!
    Delphi StringGrid控件的用法
  • 原文地址:https://www.cnblogs.com/huiyichanmian/p/12259401.html
Copyright © 2020-2023  润新知