class ManyToManyTest(APIView):
def post(self, request):
r_name = request.data.get('r_name')
u_name = request.data.get('u_name')
if not all([r_name, u_name]):
return Response({'code': 400})
# 正向
user_obj = User.objects.get(username=u_name)
role_obj = Role.objects.get(role_name=r_name)
user_obj.roles.add(role_obj)
# # 反向
# role_obj = Role.objects.get(role_name=r_name)
# user_obj = User.objects.get(username=u_name)
# role_obj.user_set.add(user_obj)
return Response({"msg": "ok"})
def get(self, request):
u_id = request.query_params.get('u_id')
r_id = request.query_params.get('r_id')
if not all([u_id, r_id]):
return Response({'code': 400})
# 正向
# user_obj = User.objects.get(id=u_id)
# role_obj = user_obj.roles.all()
# ser_obj = RoleSerializer(role_obj, many=True)
# 反向
role_obj = Role.objects.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 put(self, request):
u_id = request.query_params.get('u_id')
r_id = request.query_params.get('r_id')
if not all([u_id, r_id]):
return Response({'code': 400})
# 正向
# user_obj = User.objects.filter(id=u_id).first()
# role_obj = Role.objects.filter(id=r_id)
# user_obj.roles.set(role_obj)
# 反向
user_obj = User.objects.filter(id=u_id)
role_obj = Role.objects.filter(id=r_id).first()
role_obj.user_set.set(user_obj)
return Response({'mag': 'ok', 'code': 200})
def delete(self, request):
u_id = request.query_params.get('u_id')
r_id = request.query_params.get('r_id')
if not all([u_id, r_id]):
return Response({'code': 400, 'msg': '参数不完整'})
# 正向
user_obj = User.objects.filter(id=u_id).first()
role_obj = Role.objects.filter(id=r_id).first()
user_obj.roles.remove(role_obj)
# 反向
# user_obj = User.objects.all()
# role_obj = Role.objects.filter(id=r_id).first()
# role_obj.user_set.remove(*user_obj)
return Response({'code': 200, 'data': '删除成功'})
多对多增删改查
最新推荐文章于 2023-04-28 08:48:01 发布
这个Django视图API实现了对ManyToMany字段的增删查改操作。在post方法中,实现了角色(Role)与用户(User)的关联;get方法用于获取用户的角色或角色的用户;put方法更新用户的角色关联;delete方法移除用户与角色的关联。这些操作涵盖了正向和反向关系的处理。
摘要由CSDN通过智能技术生成