从与外键相关的模型中获取数据

[英]Fetch data from models related with foreign key


I have one model which is related to User model with Foreign key :

我有一个模型是关于外钥用户模型的:

class UserProfile(models.Model):
    user        = models.ForeignKey(User)
    gender      = models.CharField(max_length=10)
    credits     = models.IntegerField()
    ...

Now I want to fetch user data and for this I did like this :

现在我想取回用户数据,我这样做了

profile = user.userprofile_set.select_related()

Now from profile variable I have all data which is in UserProfile model but not from User model e.g., I have gender , credits etc but not user email, name etc. which comes from User model.But I want all user related information , I know request parameter will have User instance but later I may face the same problem for other models related with Foreign key.

现在,从profile变量中,我有所有的数据都在UserProfile模型中,但不是来自User model的,例如,我有性别,学分等等,但不是来自User model的用户邮件,名字等等。但是我想要所有的用户相关信息,我知道请求参数会有用户实例,但是以后我可能会遇到与外键相关的其他模型的问题。

So Please let me know the best way to fetch User data related with Foreign key in best suitable way.

所以请让我知道最好的方法,以最好的方式获取与外键相关的用户数据。

Thanks

谢谢

1 个解决方案

#1


2  

When you use this :

当你使用这个:

profile = UserProfile.objects.select_related('user').get(pk = <pk of userprofile instance>)

It won't execute second query on when you fetch data from user table like this :

当您从用户表中获取数据时,它不会执行第二个查询:

print profile.user.email ## Won't execute second query

Now you can get all or specific fields using model_to_dict

现在您可以使用model_to_dict获得所有或特定的字段。

from django.forms.models import model_to_dict
print model_to_dict(profile.user, fields=[], exclude=[]) ## All information of user relation.
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2014/03/13/e97b5b70c1f1dfb281206492350a663b.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告