【问题标题】:How to do aritmethic operations with django queries and .count?如何使用 django 查询和 .count 进行算术运算?
【发布时间】:2021-09-05 15:10:04
【问题描述】:

我想通过使用我在数据库中拥有的对象数量并对其进行操作然后在模板中显示结果来获取一个值(所以我在上下文中传递了这个值)。我找到的答案是关于使用模型字段进行操作,这对我没有帮助。

这就是我试图在视图中做的事情。 (状态是一个带有选项的字符域,但它可以是任何东西)

def get_context_data(self, **kwargs):
    context = super(Index, self).get_context_data(**kwargs)

    amount_one = mymodel.objects.filter(status='status1').count
    amount_two = mymodel.objects.filter(status='status2').count

    total_amount = amount_one + amount_two
    result_amount = (amount_one * 100) // total_amount

    context['result'] = result_amount

    return context

这行不通,但您可以了解我要做什么。

【问题讨论】:

    标签: django django-models django-queryset django-orm


    【解决方案1】:

    您需要使用.count() 而不是.count

    或者你可以使用aggregateCount

    status1 = Count('status', filter=Q(status='status1'))
    status2 = Count('status', filter=Q(status='status2'))
    total_amount = sum(mymodel.objects.aggregate(status1=status1, status2=status2).values())
    

    或者最简单的:

    total_amount = mymodel.objects.filter(status__in=['status1', 'status2']).count()
    

    【讨论】:

    • 是的,它应该给你TypeError: unsupported operand type(s) for +: 'method' and 'method'
    • 添加.count会得到什么结果?
    • 这是我得到的错误。将 .count 更改为 .count() 有效!泰。 status__in 对我不起作用,它说 status__in is not defined
    • 对,我有错字。应该是status__in=['status1', 'status2']。已编辑。
    【解决方案2】:

    使用方法count()。你错过了括号。

    amount_one = mymodel.objects.filter(status='status1').count()
    

    【讨论】:

      猜你喜欢
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多