gpt4 book ai didi

python - Django:根据字段的状态注释 Sum Case When

转载 作者:行者123 更新时间:2023-11-28 22:17:55 26 4
gpt4 key购买 nike

在我的应用程序中,我需要获取过去 30 天内每天的所有交易。

在交易模型中,我有一个货币字段,如果选择的货币是英镑或美元,我想将值转换为欧元。

模型.py

class Transaction(TimeMixIn):
COMPLETED = 1
REJECTED = 2
TRANSACTION_STATUS = (
(COMPLETED, _('Completed')),
(REJECTED, _('Rejected')),
)

user = models.ForeignKey(CustomUser)
status = models.SmallIntegerField(choices=TRANSACTION_STATUS, default=COMPLETED)
amount = models.DecimalField(default=0, decimal_places=2, max_digits=7)
currency = models.CharField(max_length=3, choices=Core.CURRENCIES, default=Core.CURRENCY_EUR)

到目前为止,这是我一直在使用的:

Transaction.objects.filter(created__gte=last_month, status=Transaction.COMPLETED)
.extra({"date": "date_trunc('day', created)"})
.values("date").annotate(amount=Sum("amount"))

返回包含日期和数量的字典的查询集:

<QuerySet [{'date': datetime.datetime(2018, 6, 19, 0, 0, tzinfo=<UTC>), 'amount': Decimal('75.00')}]>

这就是我现在尝试的:

queryset = Transaction.objects.filter(created__gte=last_month, status=Transaction.COMPLETED).extra({"date": "date_trunc('day', created)"}).values('date').annotate(
amount=Sum(Case(When(currency=Core.CURRENCY_EUR, then='amount'),
When(currency=Core.CURRENCY_USD, then=F('amount') * 0.8662),
When(currency=Core.CURRENCY_GBP, then=F('amount') * 1.1413), default=0, output_field=FloatField()))
)

它正在将 gbp 或 usd 转换为欧元,但它在同一天创建了 3 个字典,而不是对它们求和。

这是它返回的内容:<QuerySet [{'date': datetime.datetime(2018, 6, 19, 0, 0, tzinfo=<UTC>), 'amount': 21.655}, {'date': datetime.datetime(2018, 6, 19, 0, 0, tzinfo=<UTC>), 'amount': 28.5325}, {'date': datetime.datetime(2018, 6, 19, 0, 0, tzinfo=<UTC>), 'amount': 25.0}]>

这就是我想要的:

<QuerySet [{'date': datetime.datetime(2018, 6, 19, 0, 0, tzinfo=<UTC>), 'amount': 75.1875}]>

最佳答案

唯一剩下的就是 order_by。这将(是的,我知道这听起来很奇怪)强制 Django 执行 GROUP BY。所以应该重写为:

queryset = Transaction.objects.filter(
created__gte=last_month,
status=Transaction.COMPLETED
).extra(
{"date": "date_trunc('day', created)"}
).values(
'date'
).annotate(
amount=Sum(Case(
When(currency=Core.CURRENCY_EUR, then='amount'),
When(currency=Core.CURRENCY_USD, then=F('amount') * 0.8662),
When(currency=Core.CURRENCY_GBP, then=F('amount') * 1.1413),
default=0,
output_field=FloatField()
))
)<b>.order_by('date')</b>

(我在这里稍微修正了格式以使其更具可读性,尤其是对于小屏幕,但它(如果我们忽略间距)与问题中的相同,除了 .order_by(..)当然。)

关于python - Django:根据字段的状态注释 Sum Case When,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50930002/

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