Django简单左连接

时间:2018-02-22 03:42:09

标签: django

如何从模型中显示所有相关值并在模板中显示为一个?

class DentalProcedures(models.Model):
    id = models.AutoField(primary_key=True)
    patient = models.ForeignKey(PatientInfo, on_delete=models.CASCADE, null=True, blank=True)
    proc_date = models.DateField(null=True, blank=True)
    proc_tooth_no = models.CharField('Tooth No./s', max_length=10, null=True, blank=True)
    procedure = models.CharField('Procedure', max_length=200, null=True, blank=True)
    amount_charged = models.IntegerField('Amount Charged', null=True, blank=True)


class DentalPayment(models.Model):
    id = models.AutoField(primary_key=True)
    procedureid = models.ForeignKey(DentalProcedures, on_delete=models.CASCADE, null=True, blank=True)
    patient = models.ForeignKey(PatientInfo, on_delete=models.CASCADE, null=True, blank=True)
    amount_paid = models.IntegerField('Amount Paid', null=True, blank=True)
    date_paid = models.DateField(null=True, blank=True)

我想显示患者的付款摘要,包括,程序名称,收费金额和付款详情。

查看

class DentalPaymentDetailView(DetailView):
    context_object_name = "payment_detail"
    model = PatientInfo
    template_name = "patient/procedure_payment_detail.html"

    def get_context_data(self, **kwargs):
        context = super(DentalPaymentDetailView, self).get_context_data(**kwargs)
        payment = DentalPayment.objects.filter(patient=self.kwargs['pk'])
        context["payment"] = payment.DentalProcedures_set.all()


        return context

1 个答案:

答案 0 :(得分:0)

如果你有一些提供patient_id的逻辑,试试这个

context["payment"] = DentalPayment.objects.filter(patient_id=patient_id).values('procedureid__procedure', 'procedureid__amount_charged', 'amount_paid', 'date_paid')


得到total amount paid

from django.db.models import Sum

total_amount = DentalPayment.objects.filter(patient_id=patient_id).aggregate(tota_amount_paid=Sum('amount_paid'))