DRF - 序列化自定义字段
models.py:
from django.db import models class UserGroup(models.Model): title = models.CharField(max_length=32) class UserInfo(models.Model): user_type_choices = ( (1, "普通用户"), (2, "管理员"), (3, "超级管理员"), ) user_type = models.IntegerField(choices=user_type_choices) username = models.CharField(max_length=32,unique=True) password = models.CharField(max_length=64) group = models.ForeignKey("UserGroup", on_delete=models.DO_NOTHING) roles = models.ManyToManyField("Role") class Role(models.Model): title = models.CharField(max_length=32)
role 表中数据
usergroup 表中数据
userinfo 表中数据
userinfo_role 表中数据
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 UserSerializers(serializers.Serializer): # 获取 UserInfo 表的 user_type 字段的 key # 变量名是任意取的,因为通过 source 指定了字段 user_type_id = serializers.CharField(source="user_type") # 获取 UserInfo 表的 user_type 字段的 value user_type_title = serializers.CharField(source="get_user_type_display") # 获取 UserInfo 表的 username 和 password 字段 username = serializers.CharField() password = serializers.CharField() # 获取 UserInfo 表关联的 UserGroup 表的 title 字段(一对多的关系) user_group = serializers.CharField(source="group.title") # 获取 UserInfo 表关联的 Role 表的 id、title 字段(多对多关系) user_role = serializers.SerializerMethodField() # 命名规则:get_变量名,user_obj 为 user 对象 def get_user_role(self, user_obj): role_list = user_obj.roles.all() ret = [] # 获取 Role 表中的数据 for item in role_list: ret.append({"id": item.id, "title": item.title}) return ret class UserInfoView(APIView): def get(self, request, *args, **kwargs): users = models.UserInfo.objects.all() ser = UserSerializers(instance=users, many=True) ret = json.dumps(ser.data, ensure_ascii=False) return HttpResponse(ret)
访问: