【问题标题】:Purpose of square brackets when doing aggregate, sum and filter进行聚合、求和和过滤时方括号的用途
【发布时间】:2020-09-22 12:25:54
【问题描述】:

在下面我试图理解['total__sum'] or 0 的目的。我试过谷歌它,但我不完全确定谷歌是什么。谁能提供一个简单的解释或指出一些相关文档的方向?

new_qs = qs.filter(updated__day=new_time.day, updated__month=new_time.month)
day_total = new_qs.totals_data()['total__sum'] or 0

def totals_data(self):
return self.aggregate(Sum("cart__total"),Avg("cart__total"))

  

【问题讨论】:

    标签: python django filter sum aggregate


    【解决方案1】:

    new_qs.totals_data()['total__sum'] or 0 表示如果new_qs.totals_data()['total__sum']bool值为False,则将发生分配 0。

    进一步扩展,bool(new_qs.totals_data()['total__sum']) 返回 False 时,day_total = new_qs.totals_data()['total__sum'] or 0 day 将是 0,否则将分配当前值。

    那么,bool(new_qs.totals_data()['total__sum']) 什么时候会返回 False?当值为Noneempty object 时。

    您可以在herehere 中了解更多信息。

    【讨论】:

      【解决方案2】:

      new_qs.totals_data() 是一个字典,您可以通过在方括号中给出键来访问它。

      我在您的代码中添加了一行以进行澄清:

      new_qs = qs.filter(updated__day=new_time.day, updated__month=new_time.month)
      dictionary_with_totals = new_qs.totals_data()
      day_total = dictionary_with_totals['total__sum'] or 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        • 2020-05-12
        • 2018-04-18
        • 2011-09-09
        • 2020-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多