InterviewSolution
Saved Bookmarks
| 1. |
Difference between select_related and prefetch_related? |
|
Answer» 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 modelsclass 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 ExecutedSELECT 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 ExecutedSELECT id, country_name FROM country WHERE id=1;SELECT state_id, state_name WHERE State WHERE country_id IN (1);``` |
|