【问题标题】:Django get users with userprofilesDjango 使用用户配置文件获取用户
【发布时间】:2015-06-13 17:09:50
【问题描述】:

如何获取用户的用户资料?

我有自己的 cmets 应用程序

型号:

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 菜鸟。谢谢。

【问题讨论】:

    标签: django profiles


    【解决方案1】:

    您可以在这里简单地使用.select_related(),因为评论已经有一个用户的外键,而用户有一个配置文件的外键:

    comments = Comment.objects.filter(
        comment_type=1, object_id=game.id).select_related('user__userprofile')
    

    .prefetch_related() 为每个查询单独查找。 .select_related() 在一个语句中获取所有内容。

    【讨论】:

    • 非常感谢。但我必须不使用“user__profile”,而是使用“user__userprofile”。
    • 糟糕,我的错。我会更正答案以匹配。
    猜你喜欢
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2016-05-27
    • 2019-04-07
    相关资源
    最近更新 更多