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'>
二、多功能版
推荐阅读
-
python学习笔记——5. 类
-
python (django) 5. serializer
-
dJangoの初习1 博客分类: Python django
-
Mac下python以及django的安装,管理,连接mysql数据库 博客分类: djangopython pythondjango
-
dJangoの初习2 博客分类: Python django
-
django 返回自增长主键 博客分类: python django自增主键保存返回
-
python—django第一个项目 博客分类: python django
-
Windows下部署python环境及基本使用 博客分类: Python django
-
django 非抽象model的继承 博客分类: python pythondjango
-
DJango表单错误CSRF verification failed. Request aborted 博客分类: Python django