Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django模型实例的递归函数_Python_Django_Recursion - Fatal编程技术网

Python django模型实例的递归函数

Python django模型实例的递归函数,python,django,recursion,Python,Django,Recursion,我想让消息视图显示导致该消息的所有其他消息。原始消息对值没有响应,应该终止递归。有更好的方法吗?(我关注的是内存过快,因为一个线程的长度通常不应该超过10-20条消息) 对。不使用递归 def get_thread(msg): messages = [] # empty message set while msg.response_to: messages.append(msg) msg = msg.response_to me

我想让消息视图显示导致该消息的所有其他消息。原始消息对值没有响应,应该终止递归。有更好的方法吗?(我关注的是内存过快,因为一个线程的长度通常不应该超过10-20条消息)


对。不使用递归

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

对。不使用递归

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

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

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次(大约1000次),这并不是什么大问题。

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

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次(大约1000次)的深度,这并不是什么大问题.

您知道哪种方法会消耗更多内存吗?通常递归方法会消耗更多内存如果是对另一条消息的响应,您的代码实际上会将初始消息追加两次。但是我有足够的想法来使用这个答案。你知道哪种方法会消耗更多的内存吗?通常递归方法会消耗更多的内存。如果初始消息是对另一条消息的响应,你的代码实际上会将其附加两次。但我有足够的想法来使用这个答案。