张元兵 发表于 2023-5-24 20:31:14

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

图纸管理系统

一、初步构建后端项目

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


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


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

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



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

4、创建数据库

一定要注意格式

5、设置Django连接数据库

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

6、创建数据库表内容

(在:apps/DrawingManagementSystem/models.py)
from django.db import models


# Create your models here.
# === 图纸管理系统 models
# 传感器分类--sensor, 项目--project, 资料-data, 图纸信息-drawing

# 公有创建时间和修改时间
class TimestampMode(models.Model):
    """
    An abstract base class model that provides selfupdating ``created`` and ``modified`` fields.
    """
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
      abstract = True# it's very important to add this line


# === 传感器类 --- Sensor:Id,name,created,modified
class Sensor(TimestampMode):
    sensor_name = models.CharField(verbose_name="传感器名称", max_length=50, unique=True, null=False, blank=False)

    # create_time = models.DateTimeField(default=timezone.now().replace(microsecond=0))

    class Meta:
      db_table = "Draw_Sensor"
      managed = True
      app_label = "DrawingManagementSystem"

    def __str__(self):
      return "%s" % (self.sensor_name)


# === 项目类 --- project:Id,name,created,modified
class Project(TimestampMode):
    project_name = models.CharField(verbose_name="项目名称", max_length=50, unique=True, null=False, blank=False)
    sensor = models.ForeignKey(verbose_name="所属传感器", to=Sensor, on_delete=models.PROTECT)

    class Meta:
      db_table = "Draw_Project"
      managed = True
      app_label = "DrawingManagementSystem"

    def __str__(self):
      return "%s" % (self.project_name)


# === 资料类 --- data:ID,name,created,modified
class Data(TimestampMode):
    data_name = models.CharField(verbose_name="资料名称", max_length=50, unique=True, null=False, blank=False)
    sensor = models.ForeignKey(verbose_name="所属传感器", to=Sensor, on_delete=models.PROTECT)
    project = models.ForeignKey(verbose_name="所属项目", to=Project, on_delete=models.PROTECT)

    class Meta:
      db_table = "Draw_Data"
      managed = True
      app_label = "DrawingManagementSystem"

    def __str__(self):
      return "%s" % (self.data_name)


# === 图纸信息 --- drawing:ID(Material_code),drawing_name,created,modified,drawing_spec,drawing_page,drawing_client_id,drawing_remark,drawing_version
class Drawing(TimestampMode):
    material_code = models.CharField(verbose_name="物料编号", max_length=50, blank=False)
    sensor = models.ForeignKey(verbose_name="所属传感器", to=Sensor, on_delete=models.PROTECT)
    project = models.ForeignKey(verbose_name="所属项目", to=Project, on_delete=models.PROTECT)
    data = models.ForeignKey(verbose_name="所属资料", to=Data, on_delete=models.PROTECT)
    drawing_name = models.CharField(verbose_name="材料名称", max_length=50, blank=False)
    drawing_spec = models.CharField(verbose_name="规格/图纸号", max_length=50, blank=False)
    drawing_page = models.CharField(verbose_name="图纸页数", max_length=50, blank=False)
    drawing_client_id = models.CharField(verbose_name="客户编号", max_length=50)
    drawing_version = models.CharField(verbose_name="版本号", max_length=50, blank=False)
    drawing_remark = models.CharField(verbose_name="备注", max_length=100)
    drawing_url = models.CharField(verbose_name="地址", max_length=100)
    is_deleted = models.IntegerField(verbose_name="逻辑删除0否1是", max_length=10, blank=False, default=0)

    class Meta:
      db_table = "Draw_Drawing"
      managed = True
      app_label = "DrawingManagementSystem"

    def __str__(self):
      return "%s" % (self.drawing_name)(1)用指令生成数据库
python manage.py makemigrations
python manage.py migrate完成后代码如下:

7、DRF接口(初步)

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

序列化:负责对象和json格式的相互转换
​        a获取数据:对象-->Json返回给前端
​        b添加、修改:json-->对象 存储在数据库中
视图:实现后台功能的核心
​        早期:视图是基于函数--FBV
​        DRF:视图基于类--CBV
路由:路由的匹配
(2)序列化
创建DrawingManagementSystem\serializer.py文件
from rest_framework import serializers
from DrawingManagementSystem.models import Sensor, Project, Data, Drawing


# ----Sensor序列化类----
class SensorSerialzer(serializers.ModelSerializer):
    class Meta:
      model = Sensor
      fields = "__all__"

# ____Project序列化类____
class ProjectSerialzer(serializers.ModelSerializer):
    class Meta:
      model = Project
      fields = "__all__"

# ____Data序列化类____
class DataSerialzer(serializers.ModelSerializer):
    class Meta:
      model = Data
      fields = "__all__"

# ____Drawing序列化类____
class DrawingSerialzer(serializers.ModelSerializer):
    class Meta:
      model = Drawing
      fields = "__all__"(3)编写view.py代码(apps\DrawingManagementSystem\views.py)
# ====== 导入模块 ======
from rest_framework.viewsets import ModelViewSet# 封装完成的ModelViewset视图集
from DrawingManagementSystem.models import Sensor, Project, Data, Drawing# 具体的类
from DrawingManagementSystem.serializer import SensorSerialzer, ProjectSerialzer, DataSerialzer, DrawingSerialzer # 序列化类

# ---Sensor视图---
class SensorViewSet(ModelViewSet):
    queryset = Sensor.objects.all()
    serializer_class = SensorSerialzer

# ---Project---
class ProjectViewSet(ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerialzer

# ---Data视图---
class DataViewSet(ModelViewSet):
    queryset = Data.objects.all()
    serializer_class = DataSerialzer

# ---Sensor视图---
class DrawingViewSet(ModelViewSet):
    queryset = Drawing.objects.all()
    serializer_class = DrawingSerialzer(4)编写urls.py代码(apps\DrawingManagementSystem\urls.py)
# ======导入模块======
from django.urls import path
from rest_framework.routers import DefaultRouter
from DrawingManagementSystem.views import SensorViewSet, ProjectViewSet, DataViewSet, DrawingViewSet

# ====1.实例化一个 DefaultRouter====
router = DefaultRouter()

# ====2.注册相应的url====
# 注册Sensor对象
router.register('Sensors', SensorViewSet, basename='Sensors') # http://127.0.0.1:8080/DrawingApi/v1/Sensors/
# 注册Sensor对象
router.register('Projects', ProjectViewSet, basename='Projects') # http://127.0.0.1:8080/DrawingApi/v1/Projects/
# 注册Sensor对象
router.register('Datas', DataViewSet, basename='Datas') # http://127.0.0.1:8080/DrawingApi/v1/Datas/
# 注册Sensor对象
router.register('Drawings', DrawingViewSet, basename='Drawings') # http://127.0.0.1:8080/DrawingApi/v1/Drawings/

urlpatterns = [

]

# ====3.附加到urlpatterns集合中====
urlpatterns += router.urls编写总urls.py代码(gveInformationSystemBE\urls.py)
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('DrawingApi/v1/',include('DrawingManagementSystem.urls')),
]编写后运行django项目
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
pip install django-filter==21.1注册到installed_apps中

完成filter的筛选类
在apps\DrawingManagementSystem新建filter.py
# =====导入模块=====
from django_filters import FilterSet
from DrawingManagementSystem.models import Sensor, Project, Data, Drawing


# ---Sensor的Filter类---
class SensorFilter(FilterSet):
    class Meta:
      model = Sensor
      fields = ('sensor_name',) # 传感器名称


# ---Project的Filter类---
class ProjectFilter(FilterSet):
    class Meta:
      model = Project
      fields = ('project_name', 'sensor') # 项目名称 所属传感器


# ---Data的Filter类---
class DataFilter(FilterSet):
    class Meta:
      model = Data
      fields = ('data_name', 'sensor', 'project') # 资料名称 所属传感器 所属项目


# ---Drawing的Filter类---
class DrawingFilter(FilterSet):
    class Meta:
      model = Drawing
      fields = ('drawing_name', 'material_code', 'drawing_spec', 'drawing_client_id')# 材料名称、物料编号、规格/图纸号、客户编号在viewset中添加筛选类
# ====== 导入模块 ======
from rest_framework.viewsets import ModelViewSet# 封装完成的ModelViewset视图集
from DrawingManagementSystem.models import Sensor, Project, Data, Drawing# 具体的类
from DrawingManagementSystem.serializer import SensorSerialzer, ProjectSerialzer, DataSerialzer, \
    DrawingSerialzer# 序列化类
from django_filters.rest_framework import DjangoFilterBackend# 实现筛选的后台模块
from DrawingManagementSystem.filter import SensorFilter, ProjectFilter, DataFilter, DrawingFilter


# ---Sensor视图---
class SensorViewSet(ModelViewSet):
    queryset = Sensor.objects.all()
    serializer_class = SensorSerialzer
    # 设定筛选的后台
    filter_backends = (DjangoFilterBackend,)
    # 指定筛选的类
    filter_class = SensorFilter

# ---Project---
class ProjectViewSet(ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerialzer
    # 设定筛选的后台
    filter_backends = (DjangoFilterBackend,)
    # 指定筛选的类
    filter_class = ProjectFilter


# ---Data视图---
class DataViewSet(ModelViewSet):
    queryset = Data.objects.all()
    serializer_class = DataSerialzer
    # 设定筛选的后台
    filter_backends = (DjangoFilterBackend,)
    # 指定筛选的类
    filter_class = DataFilter


# ---Sensor视图---
class DrawingViewSet(ModelViewSet):
    queryset = Drawing.objects.all()
    serializer_class = DrawingSerialzer
    # 设定筛选的后台
    filter_backends = (DjangoFilterBackend,)
    # 指定筛选的类
    filter_class = DrawingFilter效果如下:

(2)筛选优化——模糊匹配
# =====导入模块=====
from django_filters import FilterSet,filters
from DrawingManagementSystem.models import Sensor, Project, Data, Drawing


# ---Sensor的Filter类---
class SensorFilter(FilterSet):
    # 重新需要支持模糊匹配的字段
    sensor_name = filters.CharFilter(field_name='sensor_name',lookup_expr="icontains")
    class Meta:
      model = Sensor
      fields = ('sensor_name',) # 传感器名称


# ---Project的Filter类---
class ProjectFilter(FilterSet):
    # 重新需要支持模糊匹配的字段
    project_name = filters.CharFilter(field_name='project_name', lookup_expr="icontains")
    class Meta:
      model = Project
      fields = ('project_name', 'sensor') # 项目名称 所属传感器


# ---Data的Filter类---
class DataFilter(FilterSet):
    # 重新需要支持模糊匹配的字段
    data_name = filters.CharFilter(field_name='data_name', lookup_expr="icontains")
    class Meta:
      model = Data
      fields = ('data_name', 'sensor', 'project') # 资料名称 所属传感器 所属项目


# ---Drawing的Filter类---
class DrawingFilter(FilterSet):
    # 重新需要支持模糊匹配的字段
    drawing_name = filters.CharFilter(field_name='drawing_name', lookup_expr="icontains")
    material_code = filters.CharFilter(field_name='material_code', lookup_expr="icontains")
    drawing_spec = filters.CharFilter(field_name='drawing_spec', lookup_expr="icontains")
    drawing_client_id = filters.CharFilter(field_name='drawing_client_id', lookup_expr="icontains")
    class Meta:
      model = Drawing
      fields = ('drawing_name', 'material_code', 'drawing_spec', 'drawing_client_id')# 材料名称、物料编号、规格/图纸号、客户编号(3)全局加入筛选后台
在gveInformationSystemBE\settings.py中加入
# ======= REST Framework全局设置 ===========
REST_FRAMEWORK = {

    # ==== 设置全局的Filter_Backends ====
    'DEFAULT_FILTER_BACKENDS': [
      'django_filters.rest_framework.DjangoFilterBackend',
    ],


}这样views.py中就不需要加入
# 设定筛选的后台
    filter_backends = (DjangoFilterBackend,)修改后代码如下:
# ====== 导入模块 ======
from rest_framework.viewsets import ModelViewSet# 封装完成的ModelViewset视图集
from DrawingManagementSystem.models import Sensor, Project, Data, Drawing# 具体的类
from DrawingManagementSystem.serializer import SensorSerialzer, ProjectSerialzer, DataSerialzer, \
    DrawingSerialzer# 序列化类
from DrawingManagementSystem.filter import SensorFilter, ProjectFilter, DataFilter, DrawingFilter


# ---Sensor视图---
class SensorViewSet(ModelViewSet):
    queryset = Sensor.objects.all()
    serializer_class = SensorSerialzer

    # 指定筛选的类
    filter_class = SensorFilter

# ---Project---
class ProjectViewSet(ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerialzer

    # 指定筛选的类
    filter_class = ProjectFilter


# ---Data视图---
class DataViewSet(ModelViewSet):
    queryset = Data.objects.all()
    serializer_class = DataSerialzer

    # 指定筛选的类
    filter_class = DataFilter


# ---Sensor视图---
class DrawingViewSet(ModelViewSet):
    queryset = Drawing.objects.all()
    serializer_class = DrawingSerialzer

    # 指定筛选的类
    filter_class = DrawingFilter(4)加入搜索
筛选【filter】:一个值只能对应一个字段,需要django-filter
搜索【search】;一个值能对应多个字段,DRF自带
在gveInformationSystemBE\settings.py中加入'rest_framework.filters.SearchFilter',
# ======= REST Framework全局设置 ===========
REST_FRAMEWORK = {

    # ==== 设置全局的Filter_Backends ====
    'DEFAULT_FILTER_BACKENDS': [
      'django_filters.rest_framework.DjangoFilterBackend',
      'rest_framework.filters.SearchFilter',

    ],


}在apps\DrawingManagementSystem\views.py中加入需要搜索匹配的字段
# ---Sensor视图---
class DrawingViewSet(ModelViewSet):
    queryset = Drawing.objects.all()
    serializer_class = DrawingSerialzer

    # 指定筛选的类
    filter_class = DrawingFilter
    # 指定查找匹配的字段
    search_fields = ('drawing_name', 'material_code', 'drawing_spec', 'drawing_client_id')结果如下:

(5)加入分页
有2种,一种为全局
即在在gveInformationSystemBE\settings.py中加入
# ======= REST Framework全局设置 ===========
REST_FRAMEWORK = {

    # ==== 设置全局的Filter_Backends ====
    'DEFAULT_FILTER_BACKENDS': [
      'django_filters.rest_framework.DjangoFilterBackend',
      'rest_framework.filters.SearchFilter',

    ],
    # ===== 设置分页 ===============
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10


}还有一种为:按需分页
apps\DrawingManagementSystem下新建paginations.py
代码如下:
# ========== 导入 ===========
from rest_framework.pagination import PageNumberPagination


class MyPageNumberPagination(PageNumberPagination):
    page_size = 5
    page_query_param = "page"
    page_size_query_param = 'size'
    max_page_size = 50在apps\DrawingManagementSystem\views.py中加入:
from DrawingManagementSystem.paginations import MyPageNumberPagination
###
###
###
# ---Sensor视图---
class DrawingViewSet(ModelViewSet):
    queryset = Drawing.objects.all()
    serializer_class = DrawingSerialzer
    pagination_class = MyPageNumberPagination

    # 指定筛选的类
    filter_class = DrawingFilter
    # 指定查找匹配的字段
    search_fields = ('drawing_name', 'material_code', 'drawing_spec', 'drawing_client_id')效果如下:

9、添加Swagger文档


记得在setting中注册
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'DrawingManagementSystem',
    'rest_framework',
    'django_filters',
    'drf_yasg',
]效果如下:

想要中文注释

效果如下:


来源:https://www.cnblogs.com/lightwower/p/17428880.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 一步步完整搭建一个图纸管理系统(Django+Vue3)