Django - 在模型辅助函数中定义变量?

时间:2014-07-07 23:37:28

标签: django variables django-models helper-functions

这是我的models.py(我正在创建一个论坛):

class Post(models.Model): #users can make a post
    user = models.ForeignKey(User)
    actualPost = models.CharField(max_length=200)


class PostReply(models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(Post) #each post can have multiple replies
    replyTo = models.ForeignKey("self", blank=True, null=True) #each reply can also have multiple replies. 
                                                               #If replyTo = None, then the reply is a direct reply to the post
                                                               #If the user is replying to an existing reply, then replyTo will link to the reply which the user is replying to
    actualReply = models.CharField(max_length=200)
    replyCounter = models.IntegerField(default=0)

所以,让我们说用户创建一个帖子。有人回复帖子(基本上,将创建一个PostReply对象,其中replyTo = None - 回复指向帖子)。如果有人回复了回复,那么将创建一个PostReply对象,其中replyTo =指向该帖子的回复。

我需要给每个回复一个柜台。如果回复是对帖子的直接回复(replyTo = None),则给出一个0的计数器。如果是对回复的回复,则给出1的计数器。如果是对回复的回复回复,给出2等的计数器。

这是我为PostReply创建的辅助函数:

def get_replyCount(self):
    if self.replyTo: #if the reply is a reply to another reply (and not a direct reply to the post)
        while self.replyTo != None:
            self = self.replyTo
            replyCounter += 1
             get_replyCount(self)
        return replyCounter
    else:
        return None

现在,如果一个名为“回复”的变量' (这是一个PostReply对象)传递给模板和模板,如果我这样做

{{ reply.get_replyCount }}

它给了我一个

UnboundLocalError at /urlWhichITriedToAccess/
local variable 'replyCounter' referenced before assignment

如何为模型辅助函数声明变量?我试过把它变成模型中的一个字段,但它不起作用。我也尝试在models.py的开头声明它但是没有用(出于显而易见的原因,我需要为PostReply的每个实例提供一个变量)。

1 个答案:

答案 0 :(得分:0)

尝试一些像

这样的递归函数
def get_replyCount(self):
    if self.replyTo: #if the reply is a reply to another reply (and not a direct reply to the post)
        replyCounter = 0
        while self.replyTo != None:
            self = self.replyTo
            replyCounter += get_replyCount(self) +1
        return replyCounter
    else:
        return 1

这应该可以返回正确的回复数量。 如果有多个回复,它将遍历此列表并添加" 1"对于每个对象,直到列表的结尾。 如果只有一个回复(或最后一个项目),它将跳转到else条件并返回1,计数至少为1。 但是,由于您只在答复中调用此函数,因此它始终至少为1。