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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With