【问题标题】:complex annotation in django querydjango查询中的复杂注释
【发布时间】:2016-11-04 15:54:58
【问题描述】:

当前状态:

模型.py

class Foo(models.model):
  name =  models.CharField(max_length = 50, blank = True, unique = True)

class Item(models.model):
  foo = models.ForeignKey('Foo')
  number =  models.PositiveIntegerField()

views.py

def index(request):
  stats= Foo.objects.filter(somecond=somevalue).\
  annotate(count=Count('item__number'), max=Max('item__number'))

  return render_to_response('stats.html', {'stats' : stats})

结果如预期的那样是带有附加字段的对象 Foo 的列表:count 包含与 Foo 相关的项目数和 max - 项目的最大数量。

示例:

Item1: Foo1, 12
Item2: Foo2, 100
Item3: Foo1, 10
Item4: Foo2, 78
Item5: Foo1, 6

结果:

统计数据:

Foo1, 3, 12
Foo2, 2, 100

好的。 现在我想得到更多:

class sell(models.Model):
  foo = models.ForeignKey('Foo')
  value = models.DecimalField(max_digits=10,decimal_places=2)

充满:

sell1: Foo1, 12.50
sell2: Foo2, 12.40
sell3: Foo1,  4.12
sell4: Foo2, 10.00



stats=Foo.objects.filter(somecond=somevalue).\
annotate(Count('item__number'), Max('item__number'), Sum('sell__value'))

我的期望是:

统计数据:

Foo1, 3, 12, 16.62
Foo2, 2, 100, 22.40

但结果是项目数和值的某种乘法(例如,如果卖元素是 1,并且有四个 Foo,总和是 4*sell.value)

我也试过 Sum('sell__value', distinct=True) 但没有区别。

我想要它作为模板,我想用统计数据做循环

{% for foo in stats %}
<h2>{{ foo.name }} </h2>
{{foo.count}}/{{foo.max}} 
sum of sell related with foo
{{foo.sum}}

这就是我想将 sum 插入统计信息的方式。

【问题讨论】:

    标签: django


    【解决方案1】:

    您可以找到https://stackoverflow.com/a/40443262/354420的一种可能性

    您必须使用自己的 QuerySet 创建自己的 Manager:

    然后

    both = Foo.objects.annotate_sum(Sell, 'value')
    

    【讨论】:

      【解决方案2】:

      我选择解决方案

      stats=Foo.objects.filter(somecond=somevalue).annotate(Count('item__number'), Max('item__number')).in_bulk()
      sells=Foo.objects.filter(somecond=somevalue).annotate(Sum('sell__value')).in_bulk()
      for key, stat in stats.items():
        setattr(stat,'sell__value__sum',sells[key].sell__value__sum)
      

      我知道 in_bulk() 调用了两个 sql,但这对我来说不是问题。我的另一个答案调用一个 sql。

      【讨论】:

        猜你喜欢
        • 2013-03-19
        • 2014-12-22
        • 2015-03-27
        • 2015-10-29
        • 2013-04-25
        • 2014-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多