如何获得带有用户个人资料的用户?
我有自己的评论应用
模型:
APPS = (
(1, 'Game'),
(2, 'Article'),
(3, 'CMS'),
(4, 'User profile'),
)
comment_type = models.IntegerField(choices=APPS,
default=1,
verbose_name="Comment Type")
object_id = models.IntegerField(default=0)
user = models.ForeignKey(User, null = True, blank = False, related_name='user')
看法:
context = {
...
'comments': Comment.objects.filter(comment_type=1, object_id=game_id),
...
}
用户资料:
class UserProfile(models.Model):
user = models.OneToOneField(User)
signature = models.TextField(blank=True)
我的看法是:
{% for comment in comments %}
....
{{ comment.user.profile.signature }}
{% endfor %}
我是django新秀。谢谢你。
您可以在此处简单地使用.select_related(),因为Comment已经具有User的外键,而User具有Profile的外键:
comments = Comment.objects.filter(
comment_type=1, object_id=game.id).select_related('user__userprofile')
.prefetch_related()对每个查询进行单独的查找。.select_related()在一条语句中获取所有内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句