问题
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?
回答1:
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.
回答2:
Use django >=1.5 for custom User model use select related functionality.
user = User.objects.select_related('profile_related', 'info_related')
来源:https://stackoverflow.com/questions/19673608/automatically-select-related-for-onetoone-field