Django ORM:在后续注释中使用注释的别名

问题描述 投票:0回答:1

我想在后续表达式中重用注释的别名。我怎样才能让 Django 生成如下 SQL:

select
    a*b as x
    x/d as y
from my_table;

请注意

x
是如何在
x/d
中简单引用的,而不是扩展为
(a*b)/d
。这在 Django 中可能吗?

我想这样做的原因是因为我的查询非常大且复杂。当使用常规注释时,Django 会多次重复大型表达式,导致查询输出变得过于复杂,难以调试和确保正确性。

django orm
1个回答
0
投票

这样怎么样?

class TestListView(ListAPIView):
    queryset = Test.objects.annotate(x=F('a') * F('b'), y=F('x') / F('d'))
    ...

如果将上面的查询转换一下,则如下。

SELECT "test_test"."id", "test_test"."a", "test_test"."b", "test_test"."d", 
("test_test"."a" * "test_test"."b") AS "x", 
(("test_test"."a" * "test_test"."b") / "test_test"."d") AS "y" 
FROM "test_test"
© www.soinside.com 2019 - 2024. All rights reserved.