Granny Aching
Granny Aching

Reputation: 1435

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?

Upvotes: 4

Views: 2305

Answers (2)

Suroor Hussain
Suroor Hussain

Reputation: 41

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()

Upvotes: 4

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477265

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()

Upvotes: 5

Related Questions