3

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?

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Granny Aching
  • 1,295
  • 12
  • 37

2 Answers2

4

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()
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Hi Willem, thanks for this answer, however, there at times when you do this with a foreign key and you keep getting the warning of N+1 . I use this [package](https://pypi.org/project/nplusone/) to track the N+1 issue, how best can one solve this ? – Lutaaya Huzaifah Idris Jul 04 '23 at 17:46
2

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