1.在modle.py
中创建多对多数据库
from django.db import models
class Role(models.Model):
role_name = models.CharField(max_lenth=12,verbose_name='角色',null=True)
class User(models.Model):
name = models.CharField(max_lenth=32,verbose_name='用户',null=True)
roles = models.ManyToManyField(Role)
2.在创建一个serialzer.py
用来写序列化
from rest_framework import serializer
from .models import *
class RoleSer(serializers.ModelSerializer)
class Meta:
model = Role # 指定数据库
fields = '__all__
class UserSer(serializers.ModelSerializer):
class Meta:
model = User # 指定数据库
fields = '__all__' # 指定字段 all为所有字段
3.在views.py
中开始写逻辑
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from user.models import *
# from user.serializers import *
from .serializer import *
# Create your views here.
class UserManyToMany(ApiView):
# 展示数据
def get(serlf,request):
# 获取数据
u_id = request.query_params.get('u_id') # 获取u_id
r_id = request.query_params.get('r_id') # 获取r_id
# 验证数据
if not all([u_id,r_id]): # 判断数据是否为空
return Response({'code':4001,'msg':'参数不全'})
# 逻辑与入库
# 知道ManyToMany字段是的查询方式
user_obj = User.object.get(id=u_id)
role_obj = user_obj.roles.all()
ser_obj = RoelSer(role_obj,many=True)
# 在不知道使用ManyToMany字段的查询方式
role_obj = Role.object.get(id=r_id)
user_obj = role_obj.user_set.all()
ser_obj = UserSer(user_obj,many=True)
# 返回数据
return Response({'code':200,'data':ser_obj.data})
# 添加数据
def post(self,request):
# 获取数据
r_name = request.data.get('r_name') # 获取role_name
u_name = request.data.get('u_name') # 获取name
# 验证数据
if not all([r_name,u_name]): # 判断参数是否存在
return Response({'code':4001,'msg':'参数不全})
# 逻辑与入库
# 反向添加
# user_obj = User.object.get(name=u_name)
# role_obj = Role.object.get(role_name=r_name)
# user_obj.roles.add(role_obj)
# 反向添加
user_obj = User.object.filter(name=u_name)
role_obj = Role.object.get(role_name=r_name)
role_obj.user_set.add(*user_obj) # *号代表多条数据
return Response('code':200,'msg':'成功')