【问题标题】:Django retrieve all comments for a userDjango 检索用户的所有评论
【发布时间】:2011-03-13 21:58:49
【问题描述】:

我正在使用 django-profiles 和 django.contrib.cmets,我正在尝试在他们的个人资料中显示特定用户的所有 cmets。

这是使用来自 django-profiles 的默认 profile_detail 视图。

我已经尝试了这两种方法,但都没有返回任何对象(尽管与此查询匹配的对象确实存在):

{% for comment in profile.user.comment_set.all %}

{% for comment in profile.user.user_comments.all %}

在 django.contrib.cmets 的源代码中,Comment 模型中 user 的外键具有以下相关名称:

user = models.ForeignKey(User, verbose_name=_('user'),
                    blank=True, null=True, related_name="%(class)s_comments")

评论也有自定义管理器:

# Manager
    objects = CommentManager()

定义为:

class CommentManager(models.Manager):

    def in_moderation(self):
        """
        QuerySet for all comments currently in the moderation queue.
            """
        return self.get_query_set().filter(is_public=False, is_removed=False)

    def for_model(self, model):
        """
        QuerySet for all comments for a particular model (either an instance or
        a class).
        """
        ct = ContentType.objects.get_for_model(model)
        qs = self.get_query_set().filter(content_type=ct)
        if isinstance(model, models.Model):
            qs = qs.filter(object_pk=force_unicode(model._get_pk_val()))
        return qs

自定义管理器是否导致 .all 查询不返回任何内容?我是否正确访问反向关系?任何帮助将不胜感激。

【问题讨论】:

    标签: django django-comments profiles django-profiles


    【解决方案1】:

    相关名称已定义,因此默认的name_set 将不起作用。 related_name 的目的是覆盖该默认反向管理器名称。

     user = models.ForeignKey(User, verbose_name=_('user'),
                    blank=True, null=True, related_name="%(class)s_comments")
    

    所以用这个:

    user.comment_comments.all()
    

    【讨论】:

    • 谢谢。我使用了错误的类名(用户而不是评论)。实际上应该是:user.comment_cmets.all()。最后的“s”应该切换。
    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    相关资源
    最近更新 更多