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)
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
在Meta裏面制定對應的模型和字段,但ModelSerializer只能實現簡單的展現,複雜的展現還須要本身定製python
depth:深度追蹤ios
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爲幾就去找幾層數據庫