使用此模型:
class Mytable(models.Model):
name = models.CharField(max_length=255,)
avg = models.DecimalField(max_digits=5, decimal_places=2)
var = models.DecimalField(max_digits=5, decimal_places=2)
我在PostgreSQL中查询后成功运行:
SELECT id, name,
max(CASE WHEN id = '1' THEN avg END) as avg1,
max(CASE WHEN id = '1' THEN var END) as var1,
max(CASE WHEN id = '2' THEN avg END) as avg2,
max(CASE WHEN id = '2' THEN var END) as var2
FROM app_mytable GROUP BY name
我的问题是如何在Django中执行此查询?我写了一个查询集,但我现在不需要 写"分组"表达式。或者另一方面,在这种情况下注释的用法是什么?
q = Mytable.objects.extra(select=
{"avg1":"max(CASE WHEN id = 1 THEN avg END)",
"var1":"max(CASE WHEN id = 1 THEN var END)",
"avg2":"max(CASE WHEN id = 2 THEN avg END)",
"var2":"max(CASE WHEN id = 2 THEN var END)"
}).annotate(?)