Skip to content

Commit ac17618

Browse files
committed
Render chart using program totals
1 parent cafd51d commit ac17618

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

extlinks/programs/views.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -119,39 +119,45 @@ def _fill_chart_context(self, context, queryset_filter):
119119
eventstream_dates = []
120120
eventstream_net_change = []
121121
current_date = date.today()
122-
filtered_link_aggregate = LinkAggregate.objects.filter(queryset_filter)
123122

124-
if filtered_link_aggregate.exists():
125-
earliest_link_date = filtered_link_aggregate.earliest("full_date").full_date
123+
# Query program-level totals from top organisations since it is the
124+
# smallest totals table that's available.
125+
filtered_totals = ProgramTopOrganisationsTotal.objects.filter(queryset_filter)
126+
127+
if filtered_totals.exists():
128+
earliest_total_date = filtered_totals.earliest("full_date").full_date
126129
else:
127130
# No link information from that collection, so setting earliest_link_date
128131
# to the first of the current month
129-
earliest_link_date = current_date.replace(day=1)
132+
earliest_total_date = current_date.replace(day=1)
130133

131-
links_aggregated_date = (
132-
LinkAggregate.objects.filter(queryset_filter)
133-
.values("month", "year")
134+
# We can GROUP BY 'full_date' as if it was just year and month as
135+
# program totals always set the day to the last day of the month.
136+
program_totals = (
137+
filtered_totals.values("full_date")
134138
.annotate(
135139
net_change=Sum("total_links_added") - Sum("total_links_removed"),
136140
)
137-
.order_by("year", "month")
141+
.order_by("full_date")
138142
)
139143

140144
# Filling an array of dates that should be in the chart
141-
while current_date >= earliest_link_date:
145+
while current_date >= earliest_total_date:
142146
dates.append(current_date.strftime("%Y-%m"))
143147
# Figure out what the last month is regardless of today's date
144148
current_date = current_date.replace(day=1) - timedelta(days=1)
145149

146150
dates = dates[::-1]
147151

148-
for link in links_aggregated_date:
149-
if link["month"] < 10:
150-
date_combined = f"{link['year']}-0{link['month']}"
152+
for total in program_totals:
153+
year = total["full_date"].year
154+
month = total["full_date"].month
155+
if month < 10:
156+
date_combined = f"{year}-0{month}"
151157
else:
152-
date_combined = f"{link['year']}-{link['month']}"
158+
date_combined = f"{year}-{month}"
153159

154-
existing_link_aggregates[date_combined] = link["net_change"]
160+
existing_link_aggregates[date_combined] = total["net_change"]
155161

156162
for month_year in dates:
157163
eventstream_dates.append(month_year)

0 commit comments

Comments
 (0)