【问题标题】:recursive function for a django model instancedjango 模型实例的递归函数
【发布时间】:2009-11-25 15:13:13
【问题描述】:

我想让消息视图显示导致该消息的所有其他消息。原始消息没有 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)

【问题讨论】:

    标签: python django recursion


    【解决方案1】:

    是的。不使用递归。

    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
    

    【讨论】:

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

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

    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 深(左右),这并不是什么大问题。

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 1970-01-01
      • 2021-11-05
      • 2021-03-22
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      相关资源
      最近更新 更多