Automatically select related for OneToOne field

ⅰ亾dé卋堺 提交于 2019-12-12 10:54:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!