Django中获取登录医生邮箱并过滤统计数据失败求助
问题分析与解决
核心错误原因
你在过滤Appointment数据时,用request.user(Django自带的User对象)去匹配Appointment模型里的emailDoctor(字符串类型的邮箱字段),两者类型不匹配,导致数据库找不到对应记录。这也是用request.user.id或request.user.username无效的原因——Appointment里根本没存这些字段的值。
修复步骤
1. 修正过滤条件
将views中所有filter(emailDoctor=request.user)替换为filter(emailDoctor=request.user.email),用当前登录用户的邮箱字符串去匹配emailDoctor字段。同时补充患者数量的统计(统计该医生下的唯一患者数)。
修改后的views.py代码片段:
elif g=='Doctor': doctor_email = request.user.email # 预约总数 nbrAp = Appointment.objects.filter(emailDoctor=doctor_email).count() # 历史预约数 nbrPastAp = Appointment.objects.filter( emailDoctor=doctor_email, dateAp__lt=timezone.now() ).count() # 未来预约数 nbrFutAp = Appointment.objects.filter( emailDoctor=doctor_email, dateAp__gte=timezone.now() ).count() # 统计唯一患者数量 nbrPatients = Appointment.objects.filter( emailDoctor=doctor_email ).values('emailPatient').distinct().count() mydict = { 'nbrAp': nbrAp, 'nbrPastAp': nbrPastAp, 'nbrFutAp': nbrFutAp, 'nbrPatients': nbrPatients } return render(request, 'homepageDoctor.html', context=mydict)
2. 数据一致性检查
确保以下两点:
- 登录用户的邮箱(
request.user.email)和Appointment表中emailDoctor字段的取值完全一致(注意大小写、空格等细节); - 如果你的
Doctor模型是和Django User分开维护的,要保证Doctor.email和对应User的邮箱同步,避免数据脱节。
进阶优化建议
为了避免后续出现类似问题,建议重构模型关联:
- 在
Doctor模型中添加与Django User的一对一关联:
class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) # 去掉原有的email和password字段,直接使用User模型的对应字段 def __str__(self): return self.name
- 将
Appointment中的emailDoctor改为外键关联Doctor:
class Appointment(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, related_name='appointments') namePatient = models.CharField(max_length=50) emailPatient = models.CharField(max_length=60) dateAp = models.DateField() timeAp = models.TimeField() status = models.BooleanField() def __str__(self): return f"{self.namePatient} will have an appointment with Dr. {self.doctor.name}"
- 此时过滤代码可以简化为:
doctor = request.user.doctor nbrAp = doctor.appointments.count() nbrPastAp = doctor.appointments.filter(dateAp__lt=timezone.now()).count() # 其余统计逻辑类似
这样不仅能避免字符串匹配的问题,还能保证数据的一致性和查询效率。
内容的提问来源于stack exchange,提问作者user20709463
相关产品推荐
相关产品推荐

