Cristian Gira
Cristian Gira

Reputation: 135

Is it worth to use `select_related()` when using just one instance of a model instead of a queryset?

I'll keep it short. Say we have this database structure:

class Bird(models.Model):
    name = models.CharField()
    specie = models.CharField()

class Feather(models.Model):
    bird = models.ForeignKey(Bird)

And then we have some simple lines from an APIView:

feather_id = request.query_params['feather']
feather = Feather.objects.get(pk=feather_id)

bird_name = feather.bird.name

# a lot of lines between

bird_specie = feather.bird.specie

Does it make any difference using:

feather = Feather.objects.select_related('bird').get(pk=1)

instead of:

feather = Feather.objects.get(pk=1)

in this scenario? I saw some people using select_prefetch() in this way and i wonder if it makes any difference, if not, which one should you use? Normally i agree that select_prefetch() is useful for optimization when using querysets to avoid querying each instance individually, but in this case, is it worth using it when you have just one instance in the whole APIView?

In my opinion the only difference is that another query is just made later on, but when talking about performance, it's the same.

Thanks in advance.

Upvotes: 2

Views: 879

Answers (1)

Tim Nyborg
Tim Nyborg

Reputation: 1649

Yes, it will make a difference, but it will probably be a very small difference. Selecting the related tables at the same time eliminates the time required for additional round trips to the database, likely a few milliseconds at most.

This may only matter to you if you have higher latency connecting to the database, there are many related tables that will be fetched in turn, and/or the apiview has very high load (and every millisecond counts).

I generally use select_related() on single object queries, but as a stylistic choice rather than a performance choice: to indicate which other models are going to be fetched and used (explicit is better than implicit).

Upvotes: 2

Related Questions