Django包含事件(约会)计数的用户列表

0pizxfdo  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(116)

在www.example.com的Django日程安排应用程序中models.py我有一个User类和一个Appointment类。如何在html页面中显示用户表,其中包含用户数量以及患者总共有多少次预约的信息。表格如下:(患者数量/患者姓名/预约次数)和结果如下:(1/user1/3; 2/user2/5 ....)

models.py
class Pricelist(models.Model):
    service=models.CharField('Name of service', max_length=60)
    price=models.DecimalField(max_digits=6, decimal_places=2)
    valid=models.BooleanField("Valid", default=False)

    def __str__(self):
        return f"{self.service} = {self.price} EUR"

class Patient(models.Model):
    name=models.CharField('Name and Surname', max_length=60)
    date_of_birth=models.CharField('Date of Birth', max_length=30, blank=True)
    address=models.CharField("Address", max_length=300)
    date_of_application=models.DateField(default=timezone.now)
    is_active=models.BooleanField(default=False)
    description = models.TextField(blank=True)

    def __str__(self):
        return self.name

class Appointment(models.Model):
id = models.AutoField(primary_key=True)
user=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, limit_choices_to={'active': True},)
appointment=models.ForeignKey(Pricelist, on_delete=models.CASCADE, null=True, blank=True)
day=models.DateField(default=date)
time_service = models.CharField(max_length=10, choices=TIME-CHOICE, default="16:00")
is_paid = models.BooleanField(default=False)

def __str__(self):
return f"{self.user.name} | dan:{self.day} | time:{self.time_service} | service:{self.service.price}"
    
    class Meta:
        db_table = "tblappointment"

我在www.example.com中通过ID获取每个患者的信息view.py:

def patient_statistics(request, patient_id):
     patient = Patients.objects.get(pk=patient_id)
     appointments = patient.appointment_set.all()
     appointment_count = patient.appointment_set.all().count()
     total_price = terms.aggregate(sum=Sum('treatment__price'))['sum']
     return render(request, 'patients/patient_statistics.html', {"appointment_count":appointment_count, "patient":patient, 'terms':terms, 'total_price':total_price})

但我不知道如何做一个病人和治疗次数的汇总表。我在寻求帮助。

vddsk6oq

vddsk6oq1#

您可以使用以下命令**.annotate(…)**[Django-doc]:

from django.db.models import Count

Patient.objects.annotate(appointments=Count('appointment_set'))

从这个QuerySet产生的Patient对象将有一个额外的属性.appointments,所以在你看来,你用途:

from django.db.models import Count

def patient_statistics(request):
    patients = Patients.objects.annotate(appointments=Count('appointment_set'))
    return render(
        request, 'patients/patient_statistics.html', {'patients': patients}
    )

你可以这样做:

{% for patient in patients %}
  {{ patient }}: {{ patient.appointments }}<br>
{% endfor %}

相关问题