Django4全栈进阶之路21 项目实战(在线报修):创建App应用和Model模型
- 创建应用App
-
python manage.py startapp RepairApp
-
- 创建模型
在models.py文件中定义一个Repair模型来表示报修单,其中包含以下字段:
-
- repair_id: 报修单号
- repair_time: 报修时间
- repair_person: 报修人
- problem_description: 问题描述
- service_person: 接单人
- response_time: 首次回应时间
- progress: 处理进度
-
from django.db import models # Create your models here. from django.db import models import datetime from django.db.models.signals import pre_save from django.dispatch import receiver # 报修单状态choices STATUS_CHOICES = ( ('1', '待受理'), ('2', '处理中'), ('3', '已完成'), ('4', '已撤销'), ) class Repair(models.Model): repair_id = models.CharField(max_length=20, unique=True, verbose_name="报修单号") repair_time = models.DateTimeField(auto_now_add=True, verbose_name="报修时间") emp_id = models.CharField(max_length=20) repair_person = models.CharField(max_length=20, verbose_name="报修人") repair_description = models.TextField(verbose_name="问题描述") receiver = models.CharField(max_length=20, verbose_name="接单人", null=True, blank=True) first_response_time = models.DateTimeField(null=True, blank=True, verbose_name="首次回应时间") process_status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='1', verbose_name="处理进度") created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间") update_time = models.DateTimeField(auto_now=True, verbose_name="最后修改时间") def __str__(self): return self.repair_id class Meta: verbose_name = "报修单" verbose_name_plural = "报修单" ordering = ['-repair_time'] @receiver(pre_save, sender=Repair) def auto_generate_repair_id(sender, instance, **kwargs): if not instance.repair_id: # 生成年月 year_month = datetime.datetime.now().strftime("%Y%m") # 查找当月最大的流水号 last_repair = Repair.objects.filter(repair_id__startswith=year_month).order_by('-repair_id').first() if last_repair: # 如果存在,流水号为最大报修单号加1 max_id = int(last_repair.repair_id[-4:]) new_id = f"{year_month}{max_id + 1:04}" else: # 如果不存在,流水号从0001开始 new_id = f"{year_month}0001" instance.repair_id = new_id