序列化
- 定义模型类
from django.db import models
# Create your models here.
class StuModel(models.Model):
SEX_CHOICES = (
(0, '女'),
(1, '男'),
)
name = models.CharField(max_length=10)
sex = models.SmallIntegerField(choices=SEX_CHOICES, null=True)
group = models.ForeignKey('Group', on_delete=models.SET_NULL, null=True)
role = models.ManyToManyField('Roles')
class Group(models.Model):
name = models.CharField(max_length=10)
class Roles(models.Model):
name = models.CharField(max_length=10)
- 视图函数
from django.shortcuts import render
# Create your views here.
from rest_framework import serializers
from rest_framework.views import APIView
from .models import *
from django.http import HttpResponse
import json
class MySerializer(serializers.Serializer):
name = serializers.CharField() # 普通查询
sex_field = serializers.IntegerField(source='sex') # 更改名称查询
sex = serializers.CharField(source='get_sex_display') # 内嵌chiose查询
group = serializers.CharField(source='group.name') # 关联查询
rol = serializers.SerializerMethodField() # manyToMany查询
def get_rol(self, row):
queryset = row.role.all()
resp = []
for item in queryset:
resp.append(
{
'id': item.id,
'name': item.name
},
)
return resp
class MyView(APIView):
def get(self, request):
queryset = StuModel.objects.all()
serializer = MySerializer(instance=queryset, many=True)
ret = json.dumps(serializer.data)
return HttpResponse(ret)
- 自定义序列化对象
- 自定义的序列化对象必须继承serializers.Serializer
- 该序列化对象的字段名和类型要和所要系列化的对象的一样
- 如果要自定义字段名,需要在类型里面加上source=数据库的字段名
- 多对多查询需要将字段对用成SerializerMethodField的类实例
-定义get_{field_name}的方法,在里面实现自定义的查询
- 自定义序列化对象实例化时,将所要序列化对象的queryset对象赋值给instance属性,当queryset对象不止一个时,many=True
- 模型序列化对象
class MySerializer(serializers.ModelSerializer):
# name = serializers.CharField() # 普通查询
# sex_field = serializers.IntegerField(source='sex') # 更改名称查询
# sex = serializers.CharField(source='get_sex_display') # 内嵌chiose查询
group = serializers.CharField(source='group.name') # 关联查询
rol = serializers.SerializerMethodField() # manyToMany查询
class Meta:
model = StuModel
fields = ['name', 'sex_field', 'sex', 'group', 'rol']
extra_kwargs = {
'sex_field': {'source': 'sex'},
'sex': {'source': 'get_sex_display'},
}
def get_rol(self, row):
queryset = row.role.all()
resp = []
for item in queryset:
resp.append(
{
'id': item.id,
'name': item.name
},
)
return resp
- 模型序列化需要继承ModelSerializer
- 可以在extra_kwargs定制额外的属性,参考Serializer
在Meta里面制定对应的模型和字段,但ModelSerializer只能实现简单的展示,复杂的展示还需要自己定制
depth:深度追踪
class MySerializer(serializers.ModelSerializer):
class Meta:
model = StuModel
fields = '__all__'
depth = 1
class MyView(APIView):
def get(self, request):
queryset = StuModel.objects.all()
serializer = MySerializer(instance=queryset, many=True)
ret = json.dumps(serializer.data)
return HttpResponse(ret)
在Meta里面加上加上depth = 1,就可以去取它对应的关联表的的下一层的所有数据,depth为几就去找几层