Though both the functions are used to fetch the related fields on a model but their functioning is bit different from each other. In simple words, select_related uses a foreign key relationship, i.e. using join on the query itself while on the prefetch_related there is a separate lookup and the joining on the python side. Let’s try to illustrate this via an example:
from django.db import models
class Country(models.Model):
country_name = models.CharField(max_length=5)
class State(models.Model):
state_name = models.CharField(max_length=5)
country = model.ForeignKey(Country)
>> states = State.objects.select_related(‘country’).all()
>> for state in states:
… print(state.state_name)
```Query Executed
SELECT state_id, state_name, country_name FROM State INNER JOIN Country ON (State.country_id = Country.id)
```
>> country = Country.objects.prefetch_related(‘state’).get(id=1)
>> for state in country.state.all():
… print(state.state_name)
```Query Executed
SELECT id, country_name FROM country WHERE id=1;
SELECT state_id, state_name WHERE State WHERE country_id IN (1);
```