Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to always prefetch_related for a specific django model

One of my models has number of related objects in it's __str__. This makes the admin site run very slow.

Is it possible to set up the model in a way that would always do prefetch_related, even if not explicitly requested?

like image 546
Granny Aching Avatar asked Sep 03 '25 02:09

Granny Aching


2 Answers

You can implement a manager [Django-doc] that will automatically add a .prefetch_related(..) to the queryset.

For example:

class MyModelManager(models.Manager):

    def get_queryset(self):
        return super().get_queryset().prefetch_related('related_model')

class MyModel(models.Model):
    # …

    _base_manager = MyModelManager()
    objects = MyModelManager()
like image 145
Willem Van Onsem Avatar answered Sep 05 '25 18:09

Willem Van Onsem


Adding as an answer since I cannot add a comment (this answer): The _base_manager attribute needs to be a class and not an object.

class MyModel(models.Model):   
    # …

    _base_manager = MyModelManager
    objects = MyModelManager()
like image 31
Suroor Hussain Avatar answered Sep 05 '25 19:09

Suroor Hussain