增删改查(原生)

Django 3.2

  1. # -*- encoding: utf-8 -*-
  2. """
  3. @Author:暗香彻骨.沐之杰 (Addis)
  4. @Contact : qyx01@qq.com
  5. @Time: 2022/6/26 17:05
  6. @Software: PyCharm
  7. @File: views_dj.py
  8. @Description:
  9. """
  10. import json
  11. import datetime
  12. from django.views import View
  13. from .models import DbStudent
  14. from django.http import HttpResponse, JsonResponse
  15. from addis_utils.api_utils import api_result
  16. from django.views.decorators.csrf import csrf_exempt
  17. """
  18. GET 查询所有 http://127.0.0.1:8081/demo/student
  19. POST 新增 http://127.0.0.1:8081/demo/student/
  20. GET 查询id http://127.0.0.1:8081/demo/student/107/
  21. PUT 更新 http://127.0.0.1:8081/demo/student/107/
  22. DELETE 删除(逻辑或物理) http://127.0.0.1:8081/demo/student/10003322/
  23. """
  24. class BookListView(View):
  25. """列表视图"""
  26. def get(self, request):
  27. """查询所有"""
  28. # 1、查询出所有记录的模型
  29. list_student = DbStudent.objects.all()
  30. # 执行原生SQL
  31. # list_student = DbStudent.objects.raw(
  32. # "SELECT * FROM db_student"
  33. # )
  34. # 2、遍历查询集,把模型对象转成字典
  35. list_stu = []
  36. for stu in list_student:
  37. dict_student = {
  38. 'id': stu.id,
  39. 'name': stu.name,
  40. 'age': stu.age,
  41. 'sex': stu.sex,
  42. 'class_name': stu.class_name,
  43. 'description': stu.description if stu.description else '',
  44. 'create_time': stu.create_time,
  45. 'updated_time': stu.updated_time
  46. }
  47. list_stu.append(dict_student)
  48. api_result["code"] = 200
  49. api_result["msg"] = "success"
  50. api_result["count"] = len(list_stu)
  51. api_result["data"] = list_stu
  52. # 3、响应
  53. return JsonResponse(api_result, json_dumps_params={'ensure_ascii': False},
  54. content_type="application/json; charset=utf-8",
  55. status=200, safe=False)
  56. def post(self, request):
  57. """新增
  58. """
  59. dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  60. print(dt)
  61. # 获取前端传入的请示体数据(json) request.body
  62. json_str_bytes = request.body
  63. # 把bytes类型的json字符串转换成json_str
  64. json_str = json_str_bytes.decode()
  65. # 利用json.loads将json字符串转换成json字典/列表
  66. stu_dict = json.loads(json_str)
  67. # 创建模型对象并保存
  68. stu = DbStudent(
  69. name=stu_dict['name'],
  70. age=stu_dict['age'],
  71. sex=stu_dict['sex'],
  72. class_name=stu_dict['class_name'],
  73. description=stu_dict['description'],
  74. create_time=datetime.datetime.now(),
  75. updated_time=stu_dict['updated_time']
  76. )
  77. stu.save()
  78. # 把修改后的模型再转换成字典
  79. json_stu = {
  80. 'id': stu.id,
  81. 'name': stu.name,
  82. 'age': stu.age,
  83. 'sex': stu.sex,
  84. 'class_name': stu.class_name,
  85. 'description': stu.description if stu.description else '',
  86. 'create_time': stu.create_time,
  87. 'updated_time': stu.updated_time
  88. }
  89. # 响应
  90. return JsonResponse(json_stu,safe=False)
  91. class BookDetailView(View):
  92. """详情视图"""
  93. def get(self, request, pk):
  94. """查询指定"""
  95. # 1、获取id
  96. # print(pk)
  97. try:
  98. # Django 方法
  99. list_student = DbStudent.objects.filter(id=pk)
  100. # 执行原生SQL
  101. # list_student = DbStudent.objects.raw(
  102. # "SELECT * FROM db_student WHERE id = '{_pk}'".format(_pk=pk)
  103. # )
  104. except DbStudent.DoesNotExist:
  105. return HttpResponse({"message": "经查询无记录"}, status=404)
  106. # print(list_student)
  107. # 2、模型对象转字典
  108. list_stu = []
  109. for stu in list_student:
  110. dict_student = {
  111. 'id': stu.id,
  112. 'name': stu.name,
  113. 'age': stu.age,
  114. 'sex': stu.sex,
  115. 'class_name': stu.class_name,
  116. 'description': stu.description if stu.description else '',
  117. 'create_time': stu.create_time,
  118. 'updated_time': stu.updated_time
  119. }
  120. list_stu.append(dict_student)
  121. api_result["code"] = 200
  122. api_result["msg"] = "success"
  123. api_result["count"] = len(list_stu)
  124. api_result["data"] = list_stu
  125. # 3、响应
  126. return JsonResponse(api_result, json_dumps_params={'ensure_ascii': False},
  127. content_type="application/json; charset=utf-8",
  128. status=200, safe=False)
  129. @csrf_exempt
  130. def put(self, request, pk):
  131. """修改指定"""
  132. # 先查询要修改的模型对象
  133. try:
  134. stu = DbStudent.objects.get(id=pk)
  135. except DbStudent.DoesNotExist:
  136. return HttpResponse({"message": "要修改的数据不存在"}, status=404)
  137. # 获取前端传入的数据(把数据转换成字典)
  138. json_str_bytes = request.body
  139. json_str = json_str_bytes.decode()
  140. stu_dict = json.loads(json_str)
  141. # stu_dict = json.loads(request.body.decode())
  142. # 重新给模型指定的属性赋值
  143. stu.name = stu_dict["name"]
  144. stu.age = stu_dict["age"]
  145. stu.sex = stu_dict["sex"]
  146. stu.class_name = stu_dict["class_name"]
  147. stu.description = stu_dict["description"]
  148. stu.create_time = stu_dict["create_time"]
  149. stu.updated_time = stu_dict["updated_time"]
  150. # 用save方法保存修改操作
  151. stu.save()
  152. # 把修改后的模型再转换成字典
  153. json_stu = {
  154. 'id': stu.id,
  155. 'name': stu.name,
  156. 'age': stu.age,
  157. 'sex': stu.sex,
  158. 'class_name': stu.class_name,
  159. 'description': stu.description if stu.description else '',
  160. 'create_time': stu.create_time,
  161. 'updated_time': stu.updated_time
  162. }
  163. # 响应
  164. return JsonResponse(json_stu)
  165. # pass
  166. def delete_physics(self, request, pk):
  167. """物理删除指定 """
  168. try:
  169. # Django 方法
  170. list_student = DbStudent.objects.get(id=pk)
  171. # 执行原生SQL
  172. # list_student = DbStudent.objects.raw(
  173. # "SELECT * FROM db_student WHERE id = '{_pk}'".format(_pk=pk)
  174. # )
  175. except DbStudent.DoesNotExist:
  176. return HttpResponse({"message": "经查询无记录"}, status=404)
  177. # 物理删除
  178. list_student.delete()
  179. # # 逻辑删除
  180. # list_student.is_deleted = 1
  181. # list_student.save()
  182. return HttpResponse(status=204)
  183. def delete(self, request, pk):
  184. """逻辑删除指定 _logic"""
  185. try:
  186. # Django 方法
  187. list_student = DbStudent.objects.get(id=pk)
  188. # 执行原生SQL
  189. # list_student = DbStudent.objects.raw(
  190. # "SELECT * FROM db_student WHERE id = '{_pk}'".format(_pk=pk)
  191. # )
  192. except DbStudent.DoesNotExist:
  193. return HttpResponse({"message": "经查询无记录"}, status=404)
  194. # 物理删除
  195. # list_student.delete()
  196. # 逻辑删除
  197. list_student.is_deleted = 1
  198. list_student.save()
  199. return HttpResponse(status=204)