Search code examples
pythonmysqldjangoormquery-cache

How to reduce the number of times a heavy objects.all query runs on foriegn key field in Django?


I found that the MySQL DB was becoming unresponsive each time I would load the admin page for a model. I investigated and found that the query Model.objects.all() was running innumerable times, I thought there was some problem because of which django caching is not working, but i verified the caching part through running the query on django shell.I am still lost, I have code similar to this :

class Car(models.Model):
    name = models.CharField(max_length=150, db_index=true)

class Accessories(models.Model):
    name = models.CharField(max_length=120, db_index=true)
    cars = models.ManyToManyField(Car)

its is very straightforward and I am still not able to understand what is going on ?


Solution

  • I am guessing you have overridden __str__ method to have all the related model objects printed somewhere like self.cars.all() , in that case you need to use the prefetch_reload mechanism like this :

    Accessories.objects.all().prefetch_related('cars')
    

    This will reduce the workload as it will prefetch the cars for a given accessory from a pre-populated queryset instead of going to the MySQL DB each time.