我有三个模型,Result
,Environment
和Test
。 Environment
和Test
是Result
中的FK。我试图在给定的Result
中为每个Environment
找到最新 Test
-本质上是为Environment
生成一个页面,该页面显示每个Result
的最新Test
。
在尝试优化PostreSQL查询的过程中,我想到了以下内容:
WITH CR
AS
(SELECT "cases_result"."test_id",
max("cases_result"."created_at") "created_at"
FROM "cases_result"
WHERE "cases_result"."environment_id" = 1001
GROUP BY "cases_result"."test_id"
)
SELECT CR.* ,
"cases_test"."id",
"cases_test"."created_at",
"cases_test"."updated_at",
"cases_test"."name",
"cases_test"."usage",
"cases_test"."result_id",
"cases_test"."health",
"cases_test"."variance",
"cases_test"."duration",
"cases_test"."required",
"cases_test"."ticket",
"cases_test"."removed_at"
FROM CR
JOIN "cases_test"
ON CR."test_id" = "cases_test"."id"
ORDER BY CR."test_id" ASC, CR."created_at" DESC
我现在尝试查看是否可以在我的models.Manager中实现此功能。我目前有:
tests = Test.objects.order_by('name')
if environment.domain != 'example.com':
tests = tests.exclude(name__startswith='sample')
results = (
self.filter(test__in=tests, environment=environment)
.select_related('test')
.prefetch_related('test__teams')
.order_by('test_id', '-created_at')
.distinct('test_id')
)
for test in tests:
for result in results:
if result.test == test:
yield result
break
我可以使用Django ORM创建此查询,还是需要使用原始SQL并获取关联的结果对象?
您可以为此使用django-cte。
他们的示例代码是:
from django_cte import CTEManager, With
class Order(Model):
objects = CTEManager()
id = AutoField(primary_key=True)
region = ForeignKey("Region", on_delete=CASCADE)
amount = IntegerField(default=0)
cte = With(
Order.objects
.values("region_id")
.annotate(total=Sum("amount"))
)
orders = (
cte.join(Order, region=cte.col.region_id)
.with_cte(cte)
.annotate(region_total=cte.col.total)
.order_by("amount")
)