DRF - 序列化的基本使用
model.py:
from django.db import models class Role(models.Model): title = models.CharField(max_length=32)
在 role 表中创建数据
方法一:平常的方法
views.py:
from drf import models import json from django.shortcuts import HttpResponse class RoleView(APIView): def get(self, request, *args, **kwargs): roles = models.Role.objects.all().values("id", "title") # 将数据转为列表 roles = list(roles) # 将数据转为 json 格式,如果想显示中文,则设置 ensure_ascii=False ret = json.dumps(roles, ensure_ascii=False) return HttpResponse(ret)
方法二:基于 rest framework
views.py:
from rest_framework.views import APIView from rest_framework import serializers from drf import models import json from django.shortcuts import HttpResponse class RoleSerializer(serializers.Serializer): # 以下两个变量的命名要和 role 的字段名一致 id = serializers.IntegerField() title = serializers.CharField() class RoleView(APIView): def get(self, request, *args, **kwargs): roles = models.Role.objects.all() ser = RoleSerializer(instance=roles, many=True) # 如果是多条数据,则将 many 设为 True;单条为 False # 进行 json 数据转换 ret = json.dumps(ser.data, ensure_ascii=False) # 如果有中文要显示的话,要将 ensure_ascii 设置为 False return HttpResponse(ret)
访问: