Question

Hi Stackoverflow people,

I am experiencing a strange issue with a select_related query in Django. I have installed the django-cities app, which lists geo information for a large number of cities. In my project model, I have created a foreignkey to the city element to store the location in my models.py.

from cities.models import City 
class Project(models.Model): 
   ...
   city = models.ForeignKey(City, blank = True, null = True)

Due to the large number of possible cities, I have created a query in my class based view which selects the related city field when creating a Project object.

from django.views.generic.edit import CreateView, UpdateView, DeleteView
from project.models import Project
class ProjectCreate(CreateView):
    queryset = Project.objects.select_related('city__country', 'city__region').all()
    template_name = 'solution/solution_create_form.html'

However, when I request the ProjectCreate class, Django still pulls an endless number of foreignkeys from the database. The logger is showing an unlimited number of the following requests.

... DEBUG (0.000) SELECT "cities_region"."id", "cities_region"."name", "cities_region"."slug", "cities_region"."name_std", "cities_region"."code", "cities_region"."country_id" FROM "cities_region" WHERE "cities_region"."id" = 3861887 ; args=(3861887,) DEBUG (0.000) SELECT "cities_country"."id", "cities_country"."name", "cities_country"."slug", "cities_country"."code", "cities_country"."population", "cities_country"."continent", "cities_country"."tld" FROM "cities_country" WHERE "cities_country"."id" = 3865483 ; args=(3865483,) D ...

How can I force the select related method when I execute the ProjectCreate class?

Thank you for your help and suggestions!

Was it helpful?

Solution

Without any testing, have you tried overriding the get_queryset method instead of using the queryset attribute? At least you will be more flexible with exception catching and other techniques.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top