使用联接3个表的注释获取数据

时间:2018-10-30 15:09:21

标签: python mysql django django-models django-rest-framework

我有3张桌子:-

    class Organization(models.Model):
       id = models.AutoField(primary_key=True)
       name = models.CharField()
       .....
       #some more field
       .....



    class Billing(models.Model):
         id = models.AutoField(primary_key=True)
         organization = models.ForeignKey(Organization)
         amount = models.IntegerField()
         .....
         #some more field
         ....

.
   class Payment(models.Model):
       id = models.AutoField(primary_key=True)
       billing = models.ForeignKey(Billing)
       organization = models.ForeignKey(Organization)
       paymentDate = models.DateTimeField()
       .....
       #some more field
       ....

只要organization完成付款,它就会每次为payment表创建一个新条目并更新billing的金额。并且有多个计费对象可用的计费表。因此,我正在使用注释计算特定组织的金额和最新付款的总和。

在使用注释查询时,我一直坚持为组织找到latest payment date

billing.objects.filter(
            orgId_id__in = organizationIdList,
            isCancel=0,
            billTime__range=(startDate, endDate)
        ).values('orgId_id').annotate(
            total_amount = Sum('amount'),
            lastest_payment_time = "HERE I AM STUCK",
        )

请帮帮我。

1 个答案:

答案 0 :(得分:1)

您可以使用OuterRefSubquery这样尝试:

 latest_payment = Payment.objects.filter(organization=OuterRef('organization')).order_by("-paymentDate")
 Billing.objects.filter(organization__id__in=organizationIdList).values('organization__id').annotate(total_amount=SUM('amount'), latest_payment=Subquery(latest_payment.values('paymentDate')[:1]))

对于此解决方案,您至少需要 Django 1.11