django模型实例的递归函数

时间:2009-11-25 15:13:14

标签: python django recursion

我想让消息视图显示导致该消息的所有其他消息。原始消息将没有response_to值,应终止递归。有一个更好的方法吗? (我正在考虑内存超速,因为一个帖子通常不应超过10到20条消息)。

def get_thread(msg,msg_set=[]):
    """
    This will get all the messages that led up to any particular message
    it takes only a message, but if the message isn't the first message
    in a thread it appends it to a message list to be returned.

    the last message in the list should be the first message created
    """
    if msg.response_to:
        return get_thread(msg.response_to, msg_set+[msg])
    return msg_set+[msg]


# Create your models here.
class Message(models.Model):
    body = models.TextField()
    sender = models.ForeignKey(User,related_name='sender')
    recipients = models.ManyToManyField(User,related_name='recipients')
    timestamp = models.DateTimeField(default=datetime.datetime.now)
    response_to = models.ForeignKey(Message,related_name='response_to')

    def thread(self):
        return get_thread(self)

2 个答案:

答案 0 :(得分:3)

是。不使用递归。

def get_thread(msg):
    messages = [] # empty message set

    while msg.response_to:  
         messages.append(msg)
         msg = msg.response_to

    messages.append(msg) # will append the original message

    return messages

答案 1 :(得分:0)

如果要限制递归深度,请添加递减计数器:

class Message(Model):

    def get_thread(self, max_length = 10):
        if self.response_to:
            thread = response_to.get_thread(max_length-1)
        else:
            thread = []
        thread.append(self)
        return thread

递归通常比循环慢,并且通常会消耗更多的内存(因为你需要用堆栈做有趣的事情来实现它),如果你只有1000深(或者说),这并不是一件大事。