from django.db.models import F
reports = Report.objects.all() # Filter reports here
# This creates LEFT OUTER JOIN with all ArticleInReport, so each
# Article will appear in result once per each report which includes it
articles_with_reports = Article.objects.annotate(
report_id=F('articleinreports__report_id')
)
# We are only interested in some reports
articles_in_reports = articles_with_reports.filter(
report_id__in=reports.values('id')
)
# As each result row is actually ArticleInReport, this effectively gives
# amount of views per article per report
articles_with_views = articles_in_reports.annotate(
views=(
F('articleinreports__ios_views')
+ F('articleinreports__android_views')
)
)
# Now do some processing in python - it's cheap
# We need dictionary to create final chart data
articles_map = {} # {Article: {report_id: article_with_view}}
for article in articles_with_views:
articles_map.setdefault(article, {})
articles_map[article][article.report_id] = article.views
article_graphs = {}
# Force-evaluate to cache Reports
# Actually this would happen automatically, but to be certain...
reports = list(reports)
# As we want all Articles, we have to fetch them
for article in Article.objects.all():
x_vals = []
y_vals = []
# Now for each report we will set article.views or 0
# this will execute only once
for report in reports:
x_vals.append(report.created_date)
if (
article in articles_map
and report.id in articles_map[article]
):
# We have views for this article in this record
y_vals.append(articles_map[article][report.id])
else:
# Defaults
y_vals.append(0)
article_graphs[article] = {
'x_vals': x_vals,
'y_vals': y_vals
}
# Finally, we have article_graphs
# {
# Article: {
# 'x_vals': [Date, Date, Date],
# 'y_vals': [100, 0, 50]
# },
# ....
# }
Articles
articles_map
article_graphs = {}
# Force-evaluate to cache Reports
# Actually this would happen automatically, but to be certain...
reports = list(reports)
for article, views_by_report in articles_map.items():
x_vals = []
y_vals = []
# Now for each report we will set article.views or 0
for report in reports:
x_vals.append(report.created_date)
y_vals.append(views_by_report.get(report.id, 0))
article_graphs[article] = {
'x_vals': x_vals,
'y_vals': y_vals
}