django框架学习二:使用ORM实现对MySql数据库增删改查的操作
Demo中以创建项目为例,使用ORM实现对数据库的增删改查操作:
models.py文件的代码:
from django.db import models class Projects(models.Model): """创建Projects模型类 """ name = models.CharField(verbose_name='项目名称', max_length=200, unique=True, help_text='项目名称') leader = models.CharField(verbose_name='负责人', max_length=50, help_text='负责人') tester = models.CharField(verbose_name='测试人员', max_length=50, help_text='测试人员') programer = models.CharField(verbose_name='开发人员', max_length=50, help_text='开发人员') publish_app = models.CharField(verbose_name='发布应用', max_length=100, help_text='发布应用') desc = models.TextField(verbose_name='简要描述', help_text='简要描述', blank=True, default='', null=True) # 定义子类Meta, 用于设置当前数据模型的元数据信息 class Meta: db_table = 'tb_projects' # 会在admin站点中, 显示一个更人性化的表名 verbose_name = '项目' verbose_name_plural = '项目' def __str__(self): return self.name
views.py文件中的代码:
from django.http import JsonResponse, Http404 from django.views import View import json from .models import Projects class PorjectsList(View): def get(self, request): # 从数据库中获取所有的项目信息 projects = Projects.objects.all() projects_list = [] # 将数据库模型实例化转化为字典类型(嵌套字典的列表) for project in projects: projects_list.append( { "name": project.name, "leader": project.leader, "tester": project.tester, "programer": project.programer, "publish_app": project.publish_app, "desc": project.desc } ) # JsonResponse第一个参数默认只能为dict字典,如果要设为其他类型,需要将safe=False return JsonResponse(data=projects_list, safe=False, status=200) def post(self, request): # 反序列化过程 data = request.body.decode("utf-8") data = json.loads(data) # 向数据库中新增项目 project = Projects.objects.create(**data) # 将创建成功的项目返回 # 将模型类对象转化成字典,然后返回 # 序列化过程 one_dict = { "id": project.id, "name": project.name, "leader": project.leader, "tester": project.tester, "programer": project.programer, "publish_app": project.publish_app, "desc": project.desc } return JsonResponse(data=one_dict, status=201) class ProjectsDetail(View): def get_object(self, pk): try: return Projects.objects.get(id=pk) except Projects.DoesNotExist: return Http404 def put(self, request, pk): # 获取指定ID为pk值的项目 project = self.get_object(pk) # 反序列化 data = json.loads(request.body.decode("utf-8")) # 更新项目 project.name = data["name"] project.leader = data["leader"] project.programer = data["programer"] project.publish_app = data["publish_app"] project.tester = data["tester"] project.desc = data["desc"] project.save() # 将模型类对象转换为字典 - 序列化 one_dict = { "id": project.id, "name": project.name, "leader": project.leader, "tester": project.tester, "programer": project.programer, "publish_app": project.publish_app, "desc": project.desc } return JsonResponse(data=one_dict, status=201) def delete(self, request, pk): # 获取指定ID为pk值的项目 project = self.get_object(pk) project.delete() return JsonResponse(data=None, safe=False, status=204)
urls.py文件中访问路径的设置:
from django.urls import path from . import views urlpatterns = [ path('projects/', views.PorjectsList.as_view()), path('projects/<int:pk>/', views.ProjectsDetail.as_view()) ]
全局urls.py文件中的设置:
path('', include('projects.urls'))
最后使用postman对接口进行测试:
1、获取项目列表-get接口:
2、新增项目接口-post接口:
3、更新项目接口:
4、删除项目接口:
针对以上代码,有哪些痛点呢?欢迎大家留言评论!