Django 检索用户的所有评论
我正在使用 django-profiles 和 django.contrib.comments,并且我试图在其个人资料中显示特定用户的所有评论。
这是使用 django-profiles 中的默认 profile_detail 视图。
我已经尝试过这两种方法,但都没有返回任何对象(尽管与此查询匹配的对象确实存在):
{% for comment in profile.user.comment_set.all %}
并且
{% for comment in profile.user.user_comments.all %}
在 django.contrib.comments 的源代码中,注释模型中用户的外键具有以下相关名称:
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 查询不返回任何内容?我是否正确访问了反向关系?任何帮助将不胜感激。
I'm using django-profiles and django.contrib.comments and I am trying to display all comments for a particular user in their profile.
This is using the default profile_detail view from django-profiles.
I've tried these two approaches and neither is returning any objects (although objects matching this query do exist):
{% for comment in profile.user.comment_set.all %}
and
{% for comment in profile.user.user_comments.all %}
In the source code for django.contrib.comments, the foreign key to user in the Comment model has the following related name:
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
Comments also has a custom manager:
# Manager
objects = CommentManager()
Which is defined as:
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
Is the custom manager causing the .all query not to return anything? Am I accessing the reverse relation correctly? Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
相关名称已定义,因此默认的
name_set
将不起作用。lated_name
的用途是覆盖默认的反向管理器名称。所以用这个:
The related name is defined so the default
name_set
will not work. The purpose ofrelated_name
is to override that default reverse manager name.So use this: