Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically select related for OneToOne field

In my Django project I have a Profile for each django User, and the Profile is related to an Info model. Both relationships are OneToOne. Since most of the time I am using both the Profile and the Info models for a user, I would like those to be selected by default so I don't hit the database again. Is there any way to do this using Django authentication?

like image 448
George Octavian Rabanca Avatar asked Oct 30 '13 04:10

George Octavian Rabanca


1 Answers

I know this has been here for a while but I am adding my solution in case someone else faces a similar situation. Django (as of v1.8 and even v1.7) allows you to customized the managers ( .objects used when querying )

You could have a manager like this for Profile:

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

Then in the model:

class Profile(models.Model):
    user = models.OneToOneField(
        User,
        primary_key=True,
        on_delete=models.CASCADE
    )

    # ... other fields 

    # the manager
    objects = ProfileManager()

    # ...

Then all your queries on Profile will automatically select the related user too.

You could extend this code to include the Info model too.

like image 196
idris Avatar answered Nov 10 '22 20:11

idris