rest_framework-序列化-1

序列化

  • 定義模型類
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只能實現簡單的展現,複雜的展現還須要本身定製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爲幾就去找幾層數據庫

相關文章
相關標籤/搜索