Reputation: 1563
I've been using a model method to return a verbose name for a model (Topic). The get_verbose_name method looks something like this:
def get_verbose_name(self):
return self.city.name
As you can see, this method retrieves another model using a ForeignKey. This ForeignKey looks something like this:
city = models.ForeignKey(City, blank = True, null = True)
Unfortunately, this model method, when called in the template using:
{{ topic.get_verbose_name }}
generates a duplicate query. For performance reasons, is it possible to use select_related in the model method? I know that you can use a model manager to use select_related by default, but for a variety of reasons, I would prefer to only use select_related for this specific method.
Thanks!
Upvotes: 0
Views: 546
Reputation: 308949
No, it's not possible to use select_related
in the model method. By the time method has been called, the topic
has already been fetched from the database, so it is too late to use select_related
.
Upvotes: 1