0

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. 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)
archer
  • 73
  • 1
  • 1
  • 8

1 Answers1

0

Ok, found the solution: you can perform the arithmetic in the annotate section above, like this:

.annotate(count=Count("car__user") * bonus + 100)
archer
  • 73
  • 1
  • 1
  • 8