2011-03-13 168 views
0

我使用的是django-profiles和django.contrib.comments,我試圖在其個人資料中顯示特定用戶的所有評論。Django檢索用戶的所有評論

這是使用django-profiles的默認profile_detail視圖。

我已經試過這兩種方法並沒有被返回的任何對象(儘管確實存在匹配該查詢對象):

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

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

在爲django.contrib中的源代碼.comments,Comment模型中用戶的外鍵具有以下相關名稱:

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 

原因造成的。所有的查詢不返回任何自定義的經理嗎?我正確訪問反向關係嗎?任何幫助,將不勝感激。

回答

0

相關名稱已定義,因此默認name_set將不起作用。 related_name的用途是覆蓋默認的反向管理器名稱。

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

所以用這個:

user.comment_comments.all() 
+0

感謝。我使用了錯誤的類名(用戶而不是評論)。其實它應該是:user.comment_comments.all()。最後的「s」應該被切換。 – 2011-03-13 22:14:55

+0

np!感謝您接收錯字 – 2011-03-13 22:17:26

相關問題