我是Django ORM
的新手,我发现在此sql
语句中难以使用Django子查询,因为我没有在select .. from (select...
中找到嵌套的django orm
示例:
这些是我的模特
class A:
published_at = models.DateTimeField(_('Published at'))
....
Class B:
pub=models.ForeignKey('A', verbose_name=_('A'), blank=True, null=True,
on_delete=models.SET_NULL)
prices= models.FloatField(_('Price'), blank=True, null=True, db_index=True)
soc = models.IntegerField(_('SOC'), blank=True, null=True,
db_index=True)
这是SQL
select DATE_FORMAT(`A`.`published_at`, '%Y-%m-%d'), sum(b)
from (
select `B`.`pub_id` as c, soc, avg(prices) as b
from B
group by c, soc
) as ch
INNER JOIN `A` ON (c = `A`.`id`)
group by DATE_FORMAT(`A`.`published_at`, '%Y-%m-%d');
在这种情况下使用`子查询是否有用?我正在使用django 1.11
请帮助
更新
当我尝试Endre Both
建议的解决方案时,出现此错误
Traceback (most recent call last):
File "/home/vagrant/.local/lib/python3.6/site-
packages/IPython/core/interactiveshell.py", line 3296, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-7-824230af12bd>", line 5, in <module>
.annotate(total=Sum('avg'))
File "/home/vagrant/.local/lib/python3.6/site-packages/django/db/models/query.py", line 948, in annotate
clone.query.add_annotation(annotation, alias, is_summary=False)
File "/home/vagrant/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 973, in add_annotation
summarize=is_summary)
File "/home/vagrant/.local/lib/python3.6/site-packages/django/db/models/aggregates.py", line 19, in resolve_expression
c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
File "/home/vagrant/.local/lib/python3.6/site-packages/django/db/models/expressions.py", line 548, in resolve_expression
c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save)
File "/home/vagrant/.local/lib/python3.6/site-packages/django/db/models/expressions.py", line 471, in resolve_expression
return query.resolve_ref(self.name, allow_joins, reuse, summarize)
File "/home/vagrant/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1472, in resolve_ref
return self.annotation_select[name]
KeyError: 'avg'
答案 0 :(得分:0)
如果您首先要计算pub_id
和soc
上的平均价格,然后对发布日期相同的酒吧的平均价格进行汇总,那么您可能正在寻找以下内容:
from django.db.models import FloatField, OuterRef, Subquery, Sum, Avg
sq = Subquery(B.objects
.filter(pub_id=OuterRef('id'), soc=OuterRef('b__soc'))
.values('pub_id', 'soc')
.annotate(avg=Avg('prices'))
.values('avg'),
output_field=FloatField()
)
results = (A.objects
.values('id', 'published_at', 'b__soc')
.annotate(avg=sq)
.values('published_at')
.annotate(total=Sum('avg'))
)
已经把这个盲文写好了,我很好奇我是否正确。这可能是原始SQL查询更易于理解的情况之一。
顺便说一句,在没有任何加权的情况下对平均值求和有什么用?