通过连接3个表使用annotate获取数据

i7uaboj4  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(233)

我有3个tables:-

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 数量。并且有多个计费对象可供计费表使用。因此,我使用annotate计算特定组织的金额和最新付款的总和。
我一直在寻找 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",
        )

请帮帮我。

xqkwcwgp

xqkwcwgp1#

您可以使用outerref和subquery进行如下尝试:

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]))

对于这个解决方案,您至少需要django1.11。

相关问题