[英]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.