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)
訪問:

