欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python (django) 5. serializer

程序员文章站 2024-03-22 17:55:28
...

一、简易版

1. api/serializers.py

# -*- coding: utf8 -*-

from rest_framework import serializers


class StudentSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()

2. api/views.py

from api.serializers import StudentSerializer

class TokenView(GenericViewSet):

    authentication_classes = []
    # permission_classes = [GradeOnePermission]
    permission_classes = []
    parser_classes = [JSONParser, ]
    throttle_classes = []

    def get(self, request, *args, **kwargs):
        name = request.query_params.get('name')
        try:
            stu = Student.objects.get(name=name)
        except Student.DoesNotExist:
            raise ParseError(_('Student does not include this name'))

        student = StudentSerializer(instance=stu, many=False)
        print(student)
        print(type(student))
        print(student.data)
        print(type(student.data))

        stu_json = json.dumps(student.data, ensure_ascii=False)

        return HttpResponse(stu_json)

3. postman

url: http://127.0.0.1:8011/api/v1/token/?name=student1&token=dbfa6b230b9ca22302a00ea918346f86

method: get

return:

{"id": 4, "name": "student1"}

console:

StudentSerializer(instance=<Student: Student object (4)>):
    id = IntegerField()
    name = CharField()
<class 'api.serializers.StudentSerializer'>
{'id': 4, 'name': 'student1'}
<class 'rest_framework.utils.serializer_helpers.ReturnDict'>

 

二、多功能版

 

相关标签: 开发