翼度科技»论坛 编程开发 python 查看内容

一步步完整搭建一个图纸管理系统(Django+Vue3)

3

主题

3

帖子

9

积分

新手上路

Rank: 1

积分
9
图纸管理系统

一、初步构建后端项目

1、打开已经创建好的虚拟环境:激活activate(推荐使用虚拟环境)并创建项目


2、导入vs code中,项目环境大致如下:


需要将终端改成虚拟环境的解释器后,简单试运行:

3、创建子app(图纸管理系统模块)



由于我们把子项目都放在apps里面了(方便统一管理)所以注册要加入一段配置

4、创建数据库

一定要注意格式

5、设置Django连接数据库

(1)安装pymysql
  1. pip install pymysql
复制代码
(2)gveInformationSystem/settings中进行相关配置
  1. DATABASES = {
  2.     'default': {
  3.         'ENGINE': 'django.db.backends.mysql',
  4.         'NAME': 'StudentDB',
  5.         'USER': 'root',
  6.         'PASSWORD': '123456',
  7.         'HOST': 'localhost',
  8.         'PORT': '3306',
  9.     }
  10. }
复制代码
(3)需要在init.py导入pymysql

6、创建数据库表内容

(在:apps/DrawingManagementSystem/models.py)
  1. from django.db import models
  2. # Create your models here.
  3. # === 图纸管理系统 models
  4. # 传感器分类--sensor, 项目--project, 资料-data, 图纸信息-drawing
  5. # 公有创建时间和修改时间
  6. class TimestampMode(models.Model):
  7.     """
  8.     An abstract base class model that provides selfupdating ``created`` and ``modified`` fields.
  9.     """
  10.     created = models.DateTimeField(auto_now_add=True)
  11.     modified = models.DateTimeField(auto_now=True)
  12.     class Meta:
  13.         abstract = True  # it's very important to add this line
  14. # === 传感器类 --- Sensor:Id,name,created,modified
  15. class Sensor(TimestampMode):
  16.     sensor_name = models.CharField(verbose_name="传感器名称", max_length=50, unique=True, null=False, blank=False)
  17.     # create_time = models.DateTimeField(default=timezone.now().replace(microsecond=0))
  18.     class Meta:
  19.         db_table = "Draw_Sensor"
  20.         managed = True
  21.         app_label = "DrawingManagementSystem"
  22.     def __str__(self):
  23.         return "%s" % (self.sensor_name)
  24. # === 项目类 --- project:Id,name,created,modified
  25. class Project(TimestampMode):
  26.     project_name = models.CharField(verbose_name="项目名称", max_length=50, unique=True, null=False, blank=False)
  27.     sensor = models.ForeignKey(verbose_name="所属传感器", to=Sensor, on_delete=models.PROTECT)
  28.     class Meta:
  29.         db_table = "Draw_Project"
  30.         managed = True
  31.         app_label = "DrawingManagementSystem"
  32.     def __str__(self):
  33.         return "%s" % (self.project_name)
  34. # === 资料类 --- data:ID,name,created,modified
  35. class Data(TimestampMode):
  36.     data_name = models.CharField(verbose_name="资料名称", max_length=50, unique=True, null=False, blank=False)
  37.     sensor = models.ForeignKey(verbose_name="所属传感器", to=Sensor, on_delete=models.PROTECT)
  38.     project = models.ForeignKey(verbose_name="所属项目", to=Project, on_delete=models.PROTECT)
  39.     class Meta:
  40.         db_table = "Draw_Data"
  41.         managed = True
  42.         app_label = "DrawingManagementSystem"
  43.     def __str__(self):
  44.         return "%s" % (self.data_name)
  45. # === 图纸信息 --- drawing:ID(Material_code),drawing_name,created,modified,drawing_spec,drawing_page,drawing_client_id,drawing_remark,drawing_version
  46. class Drawing(TimestampMode):
  47.     material_code = models.CharField(verbose_name="物料编号", max_length=50, blank=False)
  48.     sensor = models.ForeignKey(verbose_name="所属传感器", to=Sensor, on_delete=models.PROTECT)
  49.     project = models.ForeignKey(verbose_name="所属项目", to=Project, on_delete=models.PROTECT)
  50.     data = models.ForeignKey(verbose_name="所属资料", to=Data, on_delete=models.PROTECT)
  51.     drawing_name = models.CharField(verbose_name="材料名称", max_length=50, blank=False)
  52.     drawing_spec = models.CharField(verbose_name="规格/图纸号", max_length=50, blank=False)
  53.     drawing_page = models.CharField(verbose_name="图纸页数", max_length=50, blank=False)
  54.     drawing_client_id = models.CharField(verbose_name="客户编号", max_length=50)
  55.     drawing_version = models.CharField(verbose_name="版本号", max_length=50, blank=False)
  56.     drawing_remark = models.CharField(verbose_name="备注", max_length=100)
  57.     drawing_url = models.CharField(verbose_name="地址", max_length=100)
  58.     is_deleted = models.IntegerField(verbose_name="逻辑删除0否1是", max_length=10, blank=False, default=0)
  59.     class Meta:
  60.         db_table = "Draw_Drawing"
  61.         managed = True
  62.         app_label = "DrawingManagementSystem"
  63.     def __str__(self):
  64.         return "%s" % (self.drawing_name)
复制代码
(1)用指令生成数据库
  1. python manage.py makemigrations
  2. python manage.py migrate
复制代码
完成后代码如下:

7、DRF接口(初步)

(1)DRF的安装和快速实现
安装DjangoRestFramework包
  1. pip install djangorestframework==3.13.0
复制代码
在settings中导入

序列化:负责对象和json格式的相互转换
​        a获取数据:对象-->Json返回给前端
​        b添加、修改:json-->对象 存储在数据库中
视图:实现后台功能的核心
​        早期:视图是基于函数--FBV
​        DRF:视图基于类--CBV
路由:路由的匹配
(2)序列化
创建DrawingManagementSystem\serializer.py文件
  1. from rest_framework import serializers
  2. from DrawingManagementSystem.models import Sensor, Project, Data, Drawing
  3. # ----Sensor序列化类----
  4. class SensorSerialzer(serializers.ModelSerializer):
  5.     class Meta:
  6.         model = Sensor
  7.         fields = "__all__"
  8. # ____Project序列化类____
  9. class ProjectSerialzer(serializers.ModelSerializer):
  10.     class Meta:
  11.         model = Project
  12.         fields = "__all__"
  13. # ____Data序列化类____
  14. class DataSerialzer(serializers.ModelSerializer):
  15.     class Meta:
  16.         model = Data
  17.         fields = "__all__"
  18. # ____Drawing序列化类____
  19. class DrawingSerialzer(serializers.ModelSerializer):
  20.     class Meta:
  21.         model = Drawing
  22.         fields = "__all__"
复制代码
(3)编写view.py代码(apps\DrawingManagementSystem\views.py)
  1. # ====== 导入模块 ======
  2. from rest_framework.viewsets import ModelViewSet  # 封装完成的ModelViewset视图集
  3. from DrawingManagementSystem.models import Sensor, Project, Data, Drawing  # 具体的类
  4. from DrawingManagementSystem.serializer import SensorSerialzer, ProjectSerialzer, DataSerialzer, DrawingSerialzer # 序列化类
  5. # ---Sensor视图---
  6. class SensorViewSet(ModelViewSet):
  7.     queryset = Sensor.objects.all()
  8.     serializer_class = SensorSerialzer
  9. # ---Project---
  10. class ProjectViewSet(ModelViewSet):
  11.     queryset = Project.objects.all()
  12.     serializer_class = ProjectSerialzer
  13. # ---Data视图---
  14. class DataViewSet(ModelViewSet):
  15.     queryset = Data.objects.all()
  16.     serializer_class = DataSerialzer
  17. # ---Sensor视图---
  18. class DrawingViewSet(ModelViewSet):
  19.     queryset = Drawing.objects.all()
  20.     serializer_class = DrawingSerialzer
复制代码
(4)编写urls.py代码(apps\DrawingManagementSystem\urls.py)
  1. # ======导入模块======
  2. from django.urls import path
  3. from rest_framework.routers import DefaultRouter
  4. from DrawingManagementSystem.views import SensorViewSet, ProjectViewSet, DataViewSet, DrawingViewSet
  5. # ====1.实例化一个 DefaultRouter====
  6. router = DefaultRouter()
  7. # ====2.注册相应的url====
  8. # 注册Sensor对象
  9. router.register('Sensors', SensorViewSet, basename='Sensors') # http://127.0.0.1:8080/DrawingApi/v1/Sensors/
  10. # 注册Sensor对象
  11. router.register('Projects', ProjectViewSet, basename='Projects') # http://127.0.0.1:8080/DrawingApi/v1/Projects/
  12. # 注册Sensor对象
  13. router.register('Datas', DataViewSet, basename='Datas') # http://127.0.0.1:8080/DrawingApi/v1/Datas/
  14. # 注册Sensor对象
  15. router.register('Drawings', DrawingViewSet, basename='Drawings') # http://127.0.0.1:8080/DrawingApi/v1/Drawings/
  16. urlpatterns = [
  17. ]
  18. # ====3.附加到urlpatterns集合中====
  19. urlpatterns += router.urls
复制代码
编写总urls.py代码(gveInformationSystemBE\urls.py)
  1. from django.contrib import admin
  2. from django.urls import path,include
  3. urlpatterns = [
  4.     path('admin/', admin.site.urls),
  5.     path('DrawingApi/v1/',include('DrawingManagementSystem.urls')),
  6. ]
复制代码
编写后运行django项目
  1. python manage.py runserver
复制代码

浏览器输入:http://127.0.0.1:8000/DrawingApi/v1/
可以看到界面如下:

说明简单后端接口已经完成,可以简单测试下:

发现存入的时间是北美市区,将gveInformationSystemBE\settings.py中的USE_TZ = True改为:USE_TZ = False
发现存入的时间是带毫秒:参考解决方法为

或者直接在数据库软件中

可以避免存入毫秒的问题
8、DRF进阶(增删改接口、筛选、搜索、分页)

其实在网址后面加上id,就可以进行数据的删除修改

(1)DRF的筛选
步骤为:
安装:pip install django-filter
  1. pip install django-filter==21.1
复制代码
注册到installed_apps中

完成filter的筛选类
在apps\DrawingManagementSystem新建filter.py
  1. # =====导入模块=====
  2. from django_filters import FilterSet
  3. from DrawingManagementSystem.models import Sensor, Project, Data, Drawing
  4. # ---Sensor的Filter类---
  5. class SensorFilter(FilterSet):
  6.     class Meta:
  7.         model = Sensor
  8.         fields = ('sensor_name',) # 传感器名称
  9. # ---Project的Filter类---
  10. class ProjectFilter(FilterSet):
  11.     class Meta:
  12.         model = Project
  13.         fields = ('project_name', 'sensor') # 项目名称 所属传感器
  14. # ---Data的Filter类---
  15. class DataFilter(FilterSet):
  16.     class Meta:
  17.         model = Data
  18.         fields = ('data_name', 'sensor', 'project') # 资料名称 所属传感器 所属项目
  19. # ---Drawing的Filter类---
  20. class DrawingFilter(FilterSet):
  21.     class Meta:
  22.         model = Drawing
  23.         fields = ('drawing_name', 'material_code', 'drawing_spec', 'drawing_client_id')  # 材料名称、物料编号、规格/图纸号、客户编号
复制代码
在viewset中添加筛选类
  1. # ====== 导入模块 ======
  2. from rest_framework.viewsets import ModelViewSet  # 封装完成的ModelViewset视图集
  3. from DrawingManagementSystem.models import Sensor, Project, Data, Drawing  # 具体的类
  4. from DrawingManagementSystem.serializer import SensorSerialzer, ProjectSerialzer, DataSerialzer, \
  5.     DrawingSerialzer  # 序列化类
  6. from django_filters.rest_framework import DjangoFilterBackend  # 实现筛选的后台模块
  7. from DrawingManagementSystem.filter import SensorFilter, ProjectFilter, DataFilter, DrawingFilter
  8. # ---Sensor视图---
  9. class SensorViewSet(ModelViewSet):
  10.     queryset = Sensor.objects.all()
  11.     serializer_class = SensorSerialzer
  12.     # 设定筛选的后台
  13.     filter_backends = (DjangoFilterBackend,)
  14.     # 指定筛选的类
  15.     filter_class = SensorFilter
  16. # ---Project---
  17. class ProjectViewSet(ModelViewSet):
  18.     queryset = Project.objects.all()
  19.     serializer_class = ProjectSerialzer
  20.     # 设定筛选的后台
  21.     filter_backends = (DjangoFilterBackend,)
  22.     # 指定筛选的类
  23.     filter_class = ProjectFilter
  24. # ---Data视图---
  25. class DataViewSet(ModelViewSet):
  26.     queryset = Data.objects.all()
  27.     serializer_class = DataSerialzer
  28.     # 设定筛选的后台
  29.     filter_backends = (DjangoFilterBackend,)
  30.     # 指定筛选的类
  31.     filter_class = DataFilter
  32. # ---Sensor视图---
  33. class DrawingViewSet(ModelViewSet):
  34.     queryset = Drawing.objects.all()
  35.     serializer_class = DrawingSerialzer
  36.     # 设定筛选的后台
  37.     filter_backends = (DjangoFilterBackend,)
  38.     # 指定筛选的类
  39.     filter_class = DrawingFilter
复制代码
效果如下:

(2)筛选优化——模糊匹配
  1. # =====导入模块=====
  2. from django_filters import FilterSet,filters
  3. from DrawingManagementSystem.models import Sensor, Project, Data, Drawing
  4. # ---Sensor的Filter类---
  5. class SensorFilter(FilterSet):
  6.     # 重新需要支持模糊匹配的字段
  7.     sensor_name = filters.CharFilter(field_name='sensor_name',lookup_expr="icontains")
  8.     class Meta:
  9.         model = Sensor
  10.         fields = ('sensor_name',) # 传感器名称
  11. # ---Project的Filter类---
  12. class ProjectFilter(FilterSet):
  13.     # 重新需要支持模糊匹配的字段
  14.     project_name = filters.CharFilter(field_name='project_name', lookup_expr="icontains")
  15.     class Meta:
  16.         model = Project
  17.         fields = ('project_name', 'sensor') # 项目名称 所属传感器
  18. # ---Data的Filter类---
  19. class DataFilter(FilterSet):
  20.     # 重新需要支持模糊匹配的字段
  21.     data_name = filters.CharFilter(field_name='data_name', lookup_expr="icontains")
  22.     class Meta:
  23.         model = Data
  24.         fields = ('data_name', 'sensor', 'project') # 资料名称 所属传感器 所属项目
  25. # ---Drawing的Filter类---
  26. class DrawingFilter(FilterSet):
  27.     # 重新需要支持模糊匹配的字段
  28.     drawing_name = filters.CharFilter(field_name='drawing_name', lookup_expr="icontains")
  29.     material_code = filters.CharFilter(field_name='material_code', lookup_expr="icontains")
  30.     drawing_spec = filters.CharFilter(field_name='drawing_spec', lookup_expr="icontains")
  31.     drawing_client_id = filters.CharFilter(field_name='drawing_client_id', lookup_expr="icontains")
  32.     class Meta:
  33.         model = Drawing
  34.         fields = ('drawing_name', 'material_code', 'drawing_spec', 'drawing_client_id')  # 材料名称、物料编号、规格/图纸号、客户编号
复制代码
(3)全局加入筛选后台
在gveInformationSystemBE\settings.py中加入
  1. # ======= REST Framework全局设置 ===========
  2. REST_FRAMEWORK = {
  3.     # ==== 设置全局的Filter_Backends ====
  4.     'DEFAULT_FILTER_BACKENDS': [
  5.         'django_filters.rest_framework.DjangoFilterBackend',
  6.     ],
  7. }
复制代码
这样views.py中就不需要加入
  1. # 设定筛选的后台
  2.     filter_backends = (DjangoFilterBackend,)
复制代码
修改后代码如下:
  1. # ====== 导入模块 ======
  2. from rest_framework.viewsets import ModelViewSet  # 封装完成的ModelViewset视图集
  3. from DrawingManagementSystem.models import Sensor, Project, Data, Drawing  # 具体的类
  4. from DrawingManagementSystem.serializer import SensorSerialzer, ProjectSerialzer, DataSerialzer, \
  5.     DrawingSerialzer  # 序列化类
  6. from DrawingManagementSystem.filter import SensorFilter, ProjectFilter, DataFilter, DrawingFilter
  7. # ---Sensor视图---
  8. class SensorViewSet(ModelViewSet):
  9.     queryset = Sensor.objects.all()
  10.     serializer_class = SensorSerialzer
  11.     # 指定筛选的类
  12.     filter_class = SensorFilter
  13. # ---Project---
  14. class ProjectViewSet(ModelViewSet):
  15.     queryset = Project.objects.all()
  16.     serializer_class = ProjectSerialzer
  17.     # 指定筛选的类
  18.     filter_class = ProjectFilter
  19. # ---Data视图---
  20. class DataViewSet(ModelViewSet):
  21.     queryset = Data.objects.all()
  22.     serializer_class = DataSerialzer
  23.     # 指定筛选的类
  24.     filter_class = DataFilter
  25. # ---Sensor视图---
  26. class DrawingViewSet(ModelViewSet):
  27.     queryset = Drawing.objects.all()
  28.     serializer_class = DrawingSerialzer
  29.     # 指定筛选的类
  30.     filter_class = DrawingFilter
复制代码
(4)加入搜索
筛选【filter】:一个值只能对应一个字段,需要django-filter
搜索【search】;一个值能对应多个字段,DRF自带
在gveInformationSystemBE\settings.py中加入'rest_framework.filters.SearchFilter',
  1. # ======= REST Framework全局设置 ===========
  2. REST_FRAMEWORK = {
  3.     # ==== 设置全局的Filter_Backends ====
  4.     'DEFAULT_FILTER_BACKENDS': [
  5.         'django_filters.rest_framework.DjangoFilterBackend',
  6.         'rest_framework.filters.SearchFilter',
  7.     ],
  8. }
复制代码
在apps\DrawingManagementSystem\views.py中加入需要搜索匹配的字段
  1. # ---Sensor视图---
  2. class DrawingViewSet(ModelViewSet):
  3.     queryset = Drawing.objects.all()
  4.     serializer_class = DrawingSerialzer
  5.     # 指定筛选的类
  6.     filter_class = DrawingFilter
  7.     # 指定查找匹配的字段
  8.     search_fields = ('drawing_name', 'material_code', 'drawing_spec', 'drawing_client_id')
复制代码
结果如下:

(5)加入分页
有2种,一种为全局
即在在gveInformationSystemBE\settings.py中加入
  1. # ======= REST Framework全局设置 ===========
  2. REST_FRAMEWORK = {
  3.     # ==== 设置全局的Filter_Backends ====
  4.     'DEFAULT_FILTER_BACKENDS': [
  5.         'django_filters.rest_framework.DjangoFilterBackend',
  6.         'rest_framework.filters.SearchFilter',
  7.     ],
  8.     # ===== 设置分页 ===============
  9.     'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
  10.     'PAGE_SIZE': 10
  11. }
复制代码
还有一种为:按需分页
apps\DrawingManagementSystem下新建paginations.py
代码如下:
  1. # ========== 导入 ===========
  2. from rest_framework.pagination import PageNumberPagination
  3. class MyPageNumberPagination(PageNumberPagination):
  4.     page_size = 5
  5.     page_query_param = "page"
  6.     page_size_query_param = 'size'
  7.     max_page_size = 50
复制代码
在apps\DrawingManagementSystem\views.py中加入:
  1. from DrawingManagementSystem.paginations import MyPageNumberPagination
  2. ###
  3. ###
  4. ###
  5. # ---Sensor视图---
  6. class DrawingViewSet(ModelViewSet):
  7.     queryset = Drawing.objects.all()
  8.     serializer_class = DrawingSerialzer
  9.     pagination_class = MyPageNumberPagination
  10.     # 指定筛选的类
  11.     filter_class = DrawingFilter
  12.     # 指定查找匹配的字段
  13.     search_fields = ('drawing_name', 'material_code', 'drawing_spec', 'drawing_client_id')
复制代码
效果如下:

9、添加Swagger文档


记得在setting中注册
  1. INSTALLED_APPS = [
  2.     'django.contrib.admin',
  3.     'django.contrib.auth',
  4.     'django.contrib.contenttypes',
  5.     'django.contrib.sessions',
  6.     'django.contrib.messages',
  7.     'django.contrib.staticfiles',
  8.     'DrawingManagementSystem',
  9.     'rest_framework',
  10.     'django_filters',
  11.     'drf_yasg',
  12. ]
复制代码
效果如下:

想要中文注释

效果如下:


来源:https://www.cnblogs.com/lightwower/p/17428880.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具