Commit ff0ba09a authored by fred's avatar fred

performance: rewrite /listen to minimize queries

This cuts down the page from 521 queries to 3 (in my local dataset).
parent 55f8980d
...@@ -427,27 +427,27 @@ class Listen(TemplateView): ...@@ -427,27 +427,27 @@ class Listen(TemplateView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(Listen, self).get_context_data(**kwargs) context = super(Listen, self).get_context_data(**kwargs)
context['sectionName'] = "Listen" context['sectionName'] = "Listen"
context['sounds'] = SoundFile.objects.all()[:15] context['episodes'] = Episode.objects.filter(
listenable = [] soundfile__podcastable=True, soundfile__fragment=False) \
x = 0 .select_related().extra(select={
for episode in Episode.objects.all().extra(select={ 'first_diffusion': 'emissions_diffusion.datetime', },
'first_diffusion': 'emissions_diffusion.datetime', select_params=(False, True),
}, where=['''datetime = (SELECT MIN(datetime)
select_params=(False, True), FROM emissions_diffusion
where=['''datetime = (SELECT MIN(datetime) WHERE episode_id = emissions_episode.id)'''],
FROM emissions_diffusion tables=['emissions_diffusion'],).order_by('-first_diffusion') [:60]
WHERE episode_id = emissions_episode.id)'''],
tables=['emissions_diffusion'], # get all related soundfiles in a single query
).order_by('-first_diffusion'): soundfiles = {}
if x >= 60: for soundfile in SoundFile.objects.select_related().filter(podcastable=True,
break fragment=False, episode__in=[x.id for x in context['episodes']]):
elif episode.main_sound is None: soundfiles[soundfile.episode_id] = soundfile
continue
else: # replace dynamic property by a static attribute, to avoid database
x += 1 # lookups
listenable.append(episode) for episode in context['episodes']:
episode.main_sound = soundfiles.get(episode.id)
context['episodes'] = listenable
return context return context
listen = Listen.as_view() listen = Listen.as_view()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment