import json from django.db import IntegrityError from django.shortcuts import render from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from mptt_test.models import Genre # 模型 from django.forms.models import model_to_dict # Create your views here. # 插入 class mpttView(APIView): """ request {name名字},parent_id{父级id,可空} 创建一个节点 """ def post(self, request): data = request.data res = [] if 'parent_id' in data: try: res = Genre.objects.create( name=data['name'], parent=Genre.objects.get(id=data['parent_id']) ) res = {'node': model_to_dict(res), 'message': data['name'] + ' 新增叶子成功'} return Response(data=res, status=status.HTTP_200_OK) except Exception: return Response(data={"message": '错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: try: res = Genre.objects.create( name=data['name'], ) res = {'node': model_to_dict(res), 'message': data['name'] + ' 新增父级成功'} return Response(data=res, status=status.HTTP_200_OK) except Exception: return Response(data={"message": '错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) """ 得到节点 request{parent_id(节点id,可空)} """ def get(self, request): data = request.GET res = [] if 'parent_id' in data: # 给parent_id 拿到子集 res = Genre.objects.filter(parent_id=data['parent_id']).values().all() else: # 没有传name 则给第0层 res = Genre.objects.filter(parent_id=None).values().all() return Response(data=res, status=status.HTTP_200_OK) """ 删除节点 {id:节点id} """ def delete(self, request): data = request.data res = Genre.objects.filter(id=data['id']).delete() return Response(data="删除成功", status=status.HTTP_200_OK) """ 更新节点 {id:节点id,name:节点名字,parent_id:父节点id(可空)} """ def put(self, request): data = request.data if 'parent_id' in data: res = Genre.objects.filter(id=data['id']).update(name=data['name'], parent_id=data['parent_id']) else: res = Genre.objects.filter(id=data['id']).update(name=data['name']) return Response(data=res, status=status.HTTP_200_OK)