Django:User.objects.profile.all()与User.objects.get_profile()之间的区别? [英] Django: Difference between User.objects.profile.all() and User.objects.get_profile()?

查看:346
本文介绍了Django:User.objects.profile.all()与User.objects.get_profile()之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UserProfile模型,用户FK使用related_name ='profile'。

I have a UserProfile model with related_name='profile' for the User FK.

假设我有一个用户obj,user1。如果我想从user1获取UserProfile对象,在db命中和效率方面使用user1.profile.all()和user1.get_profile()有什么区别?

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?

推荐答案

这些命令都没有在Django中实际有效。但是,如果您修复了语法问题,他们会完全不同。

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

如果您想要一次获取User实例及其关联的Profile, db命中,您将使用这个:

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)

现在,您可以从用户访问配置文件通过执行 user.profile ,并且不会产生另一个数据库命中。如果您错过了 select_related ,则可以执行相同操作,但会导致另一个数据库命中。

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.

如果您已经具有一个User对象 user ,你可以执行 user.get_profile(),这将获得实际的Profile对象 - 另一个db命中。

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.

这篇关于Django:User.objects.profile.all()与User.objects.get_profile()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆