I have a query that I am trying to aggregate values so I can calculate balances more quickly than querying multiple times to get the values needed.
Overall I simply want to be able to run, but the aggregation that seems to be what would allow that isn't working:
header_accounts = custom_report.account_tree_header.all()
for header_account in header_accounts:
for regular_account in header_account.associated_regular_account_tree_accounts.all():
gl_account = regular_account.associated_account_from_chart_of_accounts
gl_entries = gl_account.range_gl # range entries
# this does not work below...
prior_credit = gl_account.old_gl.prior_credit_amount
prior_debit = gl_account.old_gl.prior_debit_amount
When I run the query below with aggregate instead of annotate, I get an AttributeError
'dict' object has no attribute '_add_hints'
How can I do this?
custom_report = AccountTree.objects.select_related().prefetch_related(
'account_tree_total', 'account_tree_regular',
Prefetch('account_tree_header', queryset=AccountTreeHeader.objects.select_related(
'associated_account_from_chart_of_accounts', 'associated_total_account_tree_account__associated_account_from_chart_of_accounts'
).prefetch_related(
'associated_regular_account_tree_accounts',
Prefetch('associated_regular_account_tree_accounts__associated_account_from_chart_of_accounts__general_ledger',
queryset=GeneralLedger.objects.select_related(
).filter(Q(
accounts_payable_line_item__property__pk__in=property_pks,
journal_line_item__property__pk__in=property_pks,
_connector=Q.OR,
), date_entered__date__gte=start_date, date_entered__date__lte=end_date).order_by('date_entered'), to_attr='range_gl'),
# ISSUE IS HERE....
Prefetch('associated_regular_account_tree_accounts__associated_account_from_chart_of_accounts__general_ledger',
queryset=GeneralLedger.objects.select_related(
).filter(Q(
accounts_payable_line_item__property__pk__in=property_pks,
journal_line_item__property__pk__in=property_pks,
_connector=Q.OR,
), date_entered__date__lte=start_date).aggregate(prior_credit_amount=Sum('credit_amount'), prior_debit_amount=Sum('debit_amount')), to_attr='old_gl'),
)),
).get(pk=custom_report.pk)
As a note in the traceback the error occurs in .get(pk=custom_report.pk)
This overall was a Subquery issue where I needed to Annotate an Aggregate to figure out the solution. The issue became that I had to pass the filters to the Prefetched aggregation, and for whatever reason that was not directly or easily possible in Django.
For example as an easy thing to reproduce:
I ended up finding a package
django-sql-utils
: https://github.com/martsberger/django-sql-utils/tree/master/sql_utilAnd it assists in the subquery pretty easily as shown below:
And that annotated aggregation of a prefetched item is possible using this code from the package: