Django ForeignKey TypeError:'RelatedManager'

时间:2014-06-10 13:29:46

标签: python django django-models

我已尝试制作评论系统(评论评论等),但我不断收到相同的错误消息......

models.py:

from django.db import models
from django.utils.translation import ugettext_lazy as _
from Site.models import SiteUser


class Discussion(models.Model):
    title = models.CharField(max_length=50, verbose_name=_('Title'))
    datetime = models.DateTimeField(auto_now_add=True)
    data = models.TextField(verbose_name=_('Data'))
    agree_count = models.PositiveIntegerField(default=0)
    tough_decision_count = models.PositiveIntegerField(default=0)
    disagree_count = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.title

    def get_comments(self):
        return self.comment_set.all().order_by('datetime')

    def get_comments_len(self):
        return self.comment_set.count()

    get_comments_len.allow_tags = True
    get_comments_len.short_description = _("Number of comments")

    class Meta:
        verbose_name = _('discussion')
        verbose_name_plural = _('discussions')


class Comment(models.Model):
    author = models.ForeignKey(SiteUser, verbose_name=_('Author'), related_name='+')
    datetime = models.DateTimeField(auto_now_add=True, verbose_name=_('Time'))
    data = models.TextField(verbose_name=_('Data'))
    part_of = models.ForeignKey(Discussion, verbose_name=_('Part of'), related_name='comments')
    on = models.ForeignKey('self', verbose_name=_('On'), related_name='child', blank=True, null=True)
    agree_count = models.PositiveIntegerField(default=0)
    tough_decision_count = models.PositiveIntegerField(default=0)
    disagree_count = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.data

    def get_child_comment(self):
        return self.child()

    class Meta:
        verbose_name = _('comment')
        verbose_name_plural = _('comments')

每当我尝试从自身访问评论时(通过" child"),我收到以下错误消息:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'RelatedManager' object is not callable

帮助!

1 个答案:

答案 0 :(得分:0)

child属性是经理(RelatedManager)。要查询它,您应该调用.all(),例如。

def get_child_comment(self):
    return self.child.all()