码迷,mamicode.com
首页 > 其他好文 > 详细

DRF 多对多序列化

时间:2020-07-15 22:59:44      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:super   save   dep   rbac   入门   连表   serialize   obj   als   

django rest framework 多对多序列化,折腾了好久,也没找到默认是怎么使用,只能自己重构了。

1 model

class Roles(models.Model):
    """
    角色信息
    """
    title = models.CharField(max_length=32,unique=True)
    label = models.CharField(max_length=64,null=True,blank=True)

class Users(models.Model):
    """
    用户信息
    """
    username = models.CharField(max_length=32,unique=True)
    nick_name = models.CharField(max_length=64,null=True,blank=True)
    password = models.CharField(max_length=128)
    state = models.BooleanField(default=False)
    is_super = models.BooleanField(default=False)
    last_login = models.DateTimeField(auto_now=True)
    create_date = models.DateTimeField(auto_now_add=True)
    #用户 与 角色 多对多关系
    roles = models.ManyToManyField(to=‘Roles‘,)

2 ,序列化

from rest_framework import serializers
from api import models


#序列化入门
class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Roles
        fields = "__all__"


#序列化进阶3,自动序列化连表(depth)
class UserSerializer(serializers.ModelSerializer):
    # 多对多
    class Meta:
        model = models.Users
        fields = "__all__"
        # 连表的深度
        depth = 1

3 视图

from api import models
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import Response
from api.serializers import rbac_serializers



#fa0410e516206b1ad9c2efa6c9d3c60e

class RolesViewSet(ModelViewSet):
    # 指定查询集
    queryset = models.Roles.objects.all()
    # 指定序列化器
    serializer_class = rbac_serializers.RoleSerializer


class UsersViewSet(ModelViewSet):
    # 指定查询集
    queryset = models.Users.objects.all()
    # 指定序列化器
    serializer_class = rbac_serializers.UserSerializer

    def perform_create(self, serializer):
        serializer.save()
        req_data = self.request.data
        roles = req_data[‘roles‘]
        # 添加多对多对象
        obj = models.Users.objects.get(id=serializer.data[‘id‘])
        for i in roles:
            role_obj = models.Roles.objects.get(id=i)
            obj.roles.add(role_obj)
            #把角色信息加入到序列化数据中
            serializer.data[‘roles‘].append({‘id‘:role_obj.id,‘title‘:role_obj.title,‘label‘:role_obj.label})
        return  serializer.data

    def perform_update(self, serializer):
        req_data = self.request.data
        roles = req_data[‘roles‘]
        user_id = req_data[‘id‘]
        obj = models.Users.objects.get(id=user_id)
        # 清空多对多对象
        obj.roles.clear()
        #添加多对多对象
        for i in roles:
            role_obj = models.Roles.objects.get(id=i[‘id‘])
            obj.roles.add(role_obj)
        serializer.save()

    def perform_destroy(self, instance):
        #清空多对多对象
        instance.roles.clear()
        instance.delete()

4 路由

from django.urls import path,include
from api.views import views_auth, views_rbac
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r‘roles‘, views_rbac.RolesViewSet)
router.register(r‘users‘, views_rbac.UsersViewSet)



urlpatterns = [
    path(r‘auth/‘, views_auth.AuthView.as_view()),
    path(‘‘,include(router.urls))
]

 

DRF 多对多序列化

标签:super   save   dep   rbac   入门   连表   serialize   obj   als   

原文地址:https://www.cnblogs.com/xiao2er/p/13306494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!