Django预约系统:如何实现患者及预约数量汇总表格展示
实现患者预约汇总表格步骤
1. 修正Model关联问题
你的Appointment模型里的user字段目前关联的是User,但要统计患者的预约数据,应该改为关联Patient模型,同时修正代码里的语法错误:
# models.py class Appointment(models.Model): id = models.AutoField(primary_key=True) # 将User关联改为Patient关联 patient = models.ForeignKey(Patient, on_delete=models.CASCADE, null=True, blank=True) appointment=models.ForeignKey(Pricelist, on_delete=models.CASCADE, null=True, blank=True) day=models.DateField(default=timezone.now) # 修正date为timezone.now(需确保导入timezone) time_service = models.CharField(max_length=10, choices=TIME_CHOICE, default="16:00") # 修正TIME-CHOICE为TIME_CHOICE is_paid = models.BooleanField(default=False) def __str__(self): return f"{self.patient.name} | 日期:{self.day} | 时间:{self.time_service} | 服务:{self.appointment.service} ({self.appointment.price} EUR)" class Meta: db_table = "tblappointment"
2. 编写汇总统计视图
创建新视图,通过annotate高效统计每个患者的预约数量:
# views.py from django.db.models import Count from .models import Patient def patient_appointment_summary(request): # 给每个Patient对象添加appointment_count字段,统计关联的预约数 patients_with_count = Patient.objects.annotate(appointment_count=Count('appointment')) return render(request, 'patients/patient_summary.html', {'patients': patients_with_count})
同时在urls.py添加对应路由:
# urls.py from django.urls import path from . import views urlpatterns = [ # 其他现有路由... path('patient-summary/', views.patient_appointment_summary, name='patient-summary'), ]
3. 编写HTML模板展示表格
创建patient_summary.html模板,循环展示患者列表并自动生成序号:
<!-- patients/patient_summary.html --> <!DOCTYPE html> <html> <head> <title>患者预约汇总</title> <style> table { border-collapse: collapse; width: 80%; margin: 20px auto; } th, td { border: 1px solid #ddd; padding: 8px; text-align: center; } th { background-color: #f2f2f2; } </style> </head> <body> <h2>患者预约汇总表</h2> <table> <thead> <tr> <th>序号</th> <th>患者姓名</th> <th>预约总数</th> </tr> </thead> <tbody> {% for patient in patients %} <tr> <!-- 用forloop.counter自动生成递增序号 --> <td>{{ forloop.counter }}</td> <td>{{ patient.name }}</td> <td>{{ patient.appointment_count }}</td> </tr> {% empty %} <tr> <td colspan="3">暂无患者数据</td> </tr> {% endfor %} </tbody> </table> </body> </html>
补充:修正单个患者统计视图
如果需要保留原单个患者统计功能,修正视图里的错误:
# 修正后的单个患者统计视图 def patient_statistics(request, patient_id): patient = Patient.objects.get(pk=patient_id) appointments = patient.appointment_set.all() appointment_count = appointments.count() # 修正字段关联,处理总价为None的情况 total_price = appointments.aggregate(sum=Sum('appointment__price'))['sum'] or 0 return render(request, 'patients/patient_statistics.html', { "appointment_count": appointment_count, "patient": patient, 'appointments': appointments, 'total_price': total_price })
内容的提问来源于stack exchange,提问作者Marko Stojanovic
相关产品推荐
相关产品推荐

