DRF - ModelSerializer 序列化

数据库结构和上篇文章一样:https://www.cnblogs.com/sch01ar/p/14295875.html

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 UserModelSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        # 获取所有的字段
        fields = "__all__"


class UserInfoView(APIView):
    def get(self, request, *args, **kwargs):
        users = models.UserInfo.objects.all()
        ser = UserModelSerializers(instance=users, many=True)
        ret = json.dumps(ser.data, ensure_ascii=False)
        return HttpResponse(ret)

访问:

一些字段显示的只剩下 id 值

也可以显示指定字段,改写 UserModelSerializers

class UserModelSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        # 显示指定字段
        fields = ["id", "username", "password"]

访问:

也可以和 serializers.CharField() 等方法配合着使用

class UserModelSerializers(serializers.ModelSerializer):
    user_type_title = serializers.CharField(source="get_user_type_display")
    user_group = serializers.CharField(source="group.title")

    class Meta:
        model = models.UserInfo
        # 显示指定字段
        fields = ["user_type_title", "id", "username", "password", "user_group"]

访问:

深度:

通过 depth 指定 UserInfo 表关联的表的层次

例如:

UserInfo 表的层次为 0,而与该表 ForeignKey 关联的 UserGroup 和 ManyToManyField 关联的 Role 表,的层次为 1

class UserModelSerializers(serializers.ModelSerializer):


    class Meta:
        model = models.UserInfo
        # 获取所有的字段
        fields = "__all__"
        # 指定层次为 1
        depth = 1

访问:

 

posted @ 2021-01-19 15:36  Sch01aR#  阅读(94)  评论(0编辑  收藏  举报