Reputation: 1435
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
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
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