I'm having troubles to understand prefetch_related
and select_related
in Django ORM. I have the following models:
class City(models.Model):
name = models.CharField(max_length=35)
state = models.ForeignKey('states.State', on_delete=models.CASCADE)
class Street(models.Model):
name = models.CharField(max_length=35)
building = models.ForeignKey('buildings.Building', on_delete=models.CASCADE)
city = models.ForeignKey('cities.City', on_delete=models.CASCADE)
And now my views.py:
cities = City.objects.all()
streets = Street.objects.all()
for city in cities:
has_bank = streets.filter(building_id=1, city=city)
if has_bank:
city.has_bank = 1
has_cinema = streets.filter(building_id=2, city=city)
if has_cinema:
city.has_cinema = 1
has_church = streets.filter(building_id=3, city=city)
if has_church:
city.has_church = 1
But now it hits the database 3 times in each time the for loop iterates. I'm trying to improve the time complexity - which is now 3N + 2 where N is number of cities, but I can't understand the select_related and prefetch_related.
Can you give me an example how would I improve this so it does not hit the database 3 times in for loop?