开发者

Django: Difference between User.objects.profile.all() and User.objects.get_profile()?

I have a UserProfile model with related_name='profi开发者_JS百科le' for the User FK.

Let's say I have a User obj, user1. If I want to get the UserProfile object from the user1, what is the difference between using user1.profile.all() and user1.get_profile() in terms of db hits and efficiency?


Neither of these commands is actually valid in Django. However, if you fix the syntax issues, they do completely different things.

If you want to get both the User instance and its associated Profile in one go, with a single db hit, you would use this:

user = User.objects.select_related('profile').get(pk=my_pk_value)

Now you can access the profile from the user by doing user.profile, and you don't incur another db hit. You can do exactly the same if you miss out select_related, but it will incur another db hit.

If you already have a User object user, you would do user.get_profile(), and that gets you the actual Profile object - with another db hit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜