gpt4 book ai didi

python - 使用 annotate 连接 3 个表获取数据

转载 作者:行者123 更新时间:2023-11-29 07:27:35 25 4
gpt4 key购买 nike

我有 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 金额。并且有多个计费对象可用计费表。因此,我正在使用注释计算为特定组织完成的金额和最新付款的总和。

我一直坚持使用注释查询为组织找到最新付款日期

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",
)

请帮帮我。

最佳答案

您可以使用 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]))

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

关于python - 使用 annotate 连接 3 个表获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53067396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com