tags:

views:

149

answers:

2

This is part of my Django application which is saving a user's profile in a special way.

class SomeUser:

    def __init__(self, request):
        self.logged_in = True
        self.profile = request.user.get_profile()
        self.favorites = self.profile.favorites.all().values_list('pk', flat=True)

    def save(self, resp):
        print "1: " + str(self.favorites)
        self.profile.favorites = self.favorites
        print "2: " + str(self.favorites)
        self.profile.save()
        return resp

Output:

1: [68, 56]
2: []

How is this even possible? I'm not fiddling with self.favorites at all! How can its value change?

EDIT: Updated the question with more info.

A: 

With just this snippet of code, it can't happen (assuming self.favorites and self.hello aren't properties). My guess would be that something somewhere else is mutating the value of self.favorites or self.hello. Is there another thread that could be doing this somewhere? Or could this perhaps be happening in a different request?

Jason Baker
I updated the question. There are no threads involved.
Deniz Dogan
+4  A: 

I'm guessing self.favorites is some kind of iterator, maybe a django QuerySet.

The first str() runs the iterator and empties it out

The second str() runs the iterator again and it is empty

Nick Craig-Wood
No, it's just a list of integers.
Deniz Dogan
Nick is correct. values_list() returns a QuerySet, not a list.
sdcvvc
It seems like it... I must have read the wrong documentation.
Deniz Dogan
Forcing evaluation by using `list(self.profile.favorites...)` in the constructor made the problem go away.
Deniz Dogan
Don't rely on documentation. Use the debugger. A set_trace in the right place would have given you both the change to step into and see what happened, and a type() would have told you it wasn't a list.The debugger is a must-know tool.
Lennart Regebro