简体   繁体   English

对 Django 子查询值执行算术运算

[英]Perform arithmetic operations on Django Subquery value

In our system, there are "Car" objects that are associated with "User" objects.在我们的系统中,有与“用户”对象相关联的“汽车”对象。 With a subquery, I want to count a specific set of Car objects, perform an arithmetic operation on the result and update the User object with that value.使用子查询,我想计算一组特定的 Car 对象,对结果执行算术运算并使用该值更新用户 object。 The problem is that subqueries are expressions, not integers and I therefore can't handle them as integers.问题是子查询是表达式,而不是整数,因此我不能将它们作为整数处理。 The code below does not work but you can see what I want to achieve.下面的代码不起作用,但您可以看到我想要实现的目标。 How should this be done?这应该怎么做?

def get_car_data():
    since = timezone.now() - timedelta(days=3)
    car_count = Subquery(
        Car.objects.filter(
            car__user=OuterRef("user"),
            car__user__blocked=False,
            created__gte=since,
        )
        .values("car__user")
        .annotate(count=Count("car__user"))
        .order_by()
        .values("count")
    )

    return {
        "car_count": Coalesce(car_count, 0, output_field=IntegerField())
    }

def calculate_values(bonus):
    data = get_car_data()

    # THIS DOES NOT WORK
    User.objects.update(car_bonus_counter=data["car_count"] * bonus + 100)

Ok, found the solution: you can perform the arithmetic in the annotate section above, like this:好的,找到了解决方案:您可以在上面的注释部分执行算术,如下所示:

.annotate(count=Count("car__user") * bonus + 100)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django-如何在m​​odels.py中的类中执行算术运算 - Django - how to perform arithmetic operations in a class in models.py 是否可以在Django model表中对另一个表中的记录进行算术运算? - Is it possible in Django model tables to perform arithmetic operations on a record in another table? 需要在Django模板标签中进行算术运算 - need to do arithmetic operations in django templates tags Django ModelAdmin 执行额外操作 - Django ModelAdmin perform extra operations 在 Django 模板语言中进行算术运算后如何将值重新分配给变量 - how to reassign value to a variable after doing arithmetic operations in Django Template Language 在 Django 模型中执行算术运算后,如何使用获得的新值更新模型中整数的值? - After performing arithmetic operations within a django model, how can I update the value of an integer in my model using the new value I obtained? 具有标量值的Django子查询 - Django Subquery with Scalar Value 可以在 django 中异步执行 db 操作吗? - It's possible to perform db operations asynchronously in django? 如何在 django 模板中进行数学运算 - how to perform mathematical operations in django template django中Model个字段之间如何进行算术运算 - How to execute arithmetic operations between Model fields in django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM