views.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import json
  2. from django.db import IntegrityError
  3. from django.shortcuts import render
  4. from rest_framework import status
  5. from rest_framework.response import Response
  6. from rest_framework.views import APIView
  7. from mptt_test.models import Genre # 模型
  8. from django.forms.models import model_to_dict
  9. # Create your views here.
  10. # 插入
  11. class mpttView(APIView):
  12. """
  13. request {name名字},parent_id{父级id,可空}
  14. 创建一个节点
  15. """
  16. def post(self, request):
  17. data = request.data
  18. res = []
  19. if 'parent_id' in data:
  20. try:
  21. res = Genre.objects.create(
  22. name=data['name'],
  23. parent=Genre.objects.get(id=data['parent_id'])
  24. )
  25. res = {'node': model_to_dict(res), 'message': data['name'] + ' 新增叶子成功'}
  26. return Response(data=res, status=status.HTTP_200_OK)
  27. except Exception:
  28. return Response(data={"message": '错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  29. else:
  30. try:
  31. res = Genre.objects.create(
  32. name=data['name'],
  33. )
  34. res = {'node': model_to_dict(res), 'message': data['name'] + ' 新增父级成功'}
  35. return Response(data=res, status=status.HTTP_200_OK)
  36. except Exception:
  37. return Response(data={"message": '错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  38. """
  39. 得到节点
  40. request{parent_id(节点id,可空)}
  41. """
  42. def get(self, request):
  43. data = request.GET
  44. res = []
  45. if 'parent_id' in data:
  46. # 给parent_id 拿到子集
  47. res = Genre.objects.filter(parent_id=data['parent_id']).values().all()
  48. else:
  49. # 没有传name 则给第0层
  50. res = Genre.objects.filter(parent_id=None).values().all()
  51. return Response(data=res, status=status.HTTP_200_OK)
  52. """
  53. 删除节点
  54. {id:节点id}
  55. """
  56. def delete(self, request):
  57. data = request.data
  58. res = Genre.objects.filter(id=data['id']).delete()
  59. return Response(data="删除成功", status=status.HTTP_200_OK)
  60. """
  61. 更新节点
  62. {id:节点id,name:节点名字,parent_id:父节点id(可空)}
  63. """
  64. def put(self, request):
  65. data = request.data
  66. if 'parent_id' in data:
  67. res = Genre.objects.filter(id=data['id']).update(name=data['name'], parent_id=data['parent_id'])
  68. else:
  69. res = Genre.objects.filter(id=data['id']).update(name=data['name'])
  70. return Response(data=res, status=status.HTTP_200_OK)