Can I specify join strategy right in a django model?

Viewed 35

Is there a way to specify a join strategy not in a query (with prefetch_related or select_related), but right in a django model (like lazy='joined' in sqlalchemy)?

1 Answers

You can define a manager to automatically apply select_related and/or prefetch_related. For example:

from django.conf import settings
from django.db import models

class ProfileManager(models.Manager):
    
    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).select_related(
            'user'
        )

class Profile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_deleted=models.CASCADE
    )
    
    objects = ProfileManager()

If you then access Profile.objects.all(), then it will automatically perform a .select_related().

Related