[Answered ]-Django duplicate SQL queries stemming from model method get_absolute_url that accesses ForeignKey relationship

1👍

✅

I would advise not to use extra_context. This will prevent reevaluating the query between two requests, which means that if you thus add an extra Scenario, and you do not restart the server, it will not "update’ the list when you ask for the scenario’s again. The demo query is even more problematic, since that runs immediately when you start the server, and thus can raise errors if you run this on a server with a database, without such demo Scenario.

You can however work with queryset which already performs a .select_related(…) on the necessary relations here, so:

from django.shortcuts import get_object_or_404


class ScenarioListView(generic.ListView):
    """View class for list of Scenarios"""
    queryset = Scenario.objects.select_related(
        'domain_subdomain', 'lang_power', 'lang_primary_non_power'
    )

    def get_context_data(self, *args, **kwargs):
        return super().get_context_data(
            *args,
            **kwargs,
            demo=get_object_or_404(self.queryset, scenario_id='demo'),
            prod=self.queryset.filter(status='PROD'),
            staged=self.queryset.filter(status='STGE'),
            experimental=self.queryset.filter(status='EXPR'),
        )

Leave a comment