Search code examples
djangodjango-commentsprofilesdjango-profiles

Django retrieve all comments for a user


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.


Solution

  • The related name is defined so the default name_set will not work. The purpose of related_name is to override that default reverse manager name.

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

    So use this:

    user.comment_comments.all()