我有一个与带有外键
的用户模型
相关的模型:
class UserProfile(models.Model):
user = models.ForeignKey(User)
gender = models.CharField(max_length=10)
credits = models.IntegerField()
...
现在我想获取用户数据,为此我这样做了:
profile = user.userprofile_set.select_related()
现在,从配置文件变量中,我拥有 UserProfile
模型中的所有数据,但不是来自 User
模型例如,我有性别、积分
等,但不是来自用户
模型的用户电子邮件、姓名
等。但我想要所有用户相关信息,我知道请求
参数将具有 User 实例
但稍后我可能会遇到与外键相关的其他模型相同的问题。
所以请让我知道以最合适的方式获取与外键
相关的用户
数据的最佳方法。
谢谢
最佳答案
当你使用这个时:
profile = UserProfile.objects.select_related('user').get(pk = <pk of userprofile instance>)
当您从 user
表中获取数据时,它不会执行第二个查询,如下所示:
print profile.user.email ## Won't execute second query
现在您可以使用model_to_dict
获取所有或特定字段
from django.forms.models import model_to_dict
print model_to_dict(profile.user, fields=[], exclude=[]) ## All information of user relation.
关于python - 从与外键相关的模型中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22370415/