如何在这个sql中使用Django Orm子查询

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

我是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'
django django-orm
1个回答
0
投票

如果您首先想要计算pub_idsoc的平均价格,然后总结那些具有相同发布日期的酒吧的平均值,您可能正在寻找:

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查询更容易理解的情况之一。

顺便说一句,在没有任何加权的情况下总结平均值有什么用呢?

© www.soinside.com 2019 - 2024. All rights reserved.