views:

99

answers:

2

i want to make message view show all other messages that led up to that message. the original message will not have a response_to value and should terminate the recursion. is there a better way to do this? (i'm looking at memory over speed, because a thread shouldn't typically be more than 10 - 20 messages long).

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)
+3  A: 

Yes. not using recursion.

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
ikkebr
do you know which method will consume more memory?
Brandon H
usually the recursive method will consume more memory
ikkebr
your code would actually append the initial message twice if it was a response to another message. but i get the idea enough to use this answer.
Brandon H
A: 

If you want to limit recursion depth, add a decrementing counter:

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

Recursion is usually slower than a loop, and usually consumes more memory (as you need to do funny things with stacks to implement it), it's not a huge deal if you are only going 1000 deep (or so).

wisty