【问题标题】:Get data using annotate with joining 3 tables使用连接 3 个表的注释获取数据
【发布时间】:2019-04-03 16:15:27
【问题描述】:

我有 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 金额。并且有多个计费对象可用的计费表。因此,我正在计算使用 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",
        )

请帮帮我。

【问题讨论】:

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


    【解决方案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

    【讨论】:

    • 非常感谢。
    • 乐于助人:)
    猜你喜欢
    • 2021-04-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2019-08-03
    相关资源
    最近更新 更多