2

I'm trying to update some "summary models" of my data without using a for loop. These summaries share many of the same field names as the data, so I feel like there should be an easy way to do some sort of Summary.objects.all().update(**Subquery(Data.objects.filter(my_key=OuterRef('my_key')).aggregate(my_value_1=Sum('my_value_1'), my_value_2=Sum('my_value_2')) or something similar and have the values in Summary be updated.

However, it's not that simple. For starters, I get the following error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. This seems to happen because of the aggregate part, as removing the aggregate fixes that error... but I need the Sum! And of course there's a different error for **Subquery(), and yet another error for .update(Subquery())


I feel like there is a very simple solution to my problem, but I just keep hitting error after error and can't figure out how to get on the right track. Any advice would be greatly appreciated.

Dr. Cyanide
  • 520
  • 1
  • 7
  • 21
  • 1
    Yes, simple solution is use RAW queries – Anup Yadav Jan 15 '19 at 14:05
  • RAW queries should be avoided when possible as they make the code harder to maintain and less portable. `aggregate` can't be used on Subqueries as it directly tries to evaluate them. Just a rough suggestion: you need to `annotate` the subquery values and then update them with an `F` reference. There is more in help in the documentation (https://docs.djangoproject.com/en/3.1/ref/models/expressions/#using-aggregates-within-a-subquery-expression) – Gnietschow Sep 29 '20 at 12:52

0 Answers0