On 10/25/07, Ryan K <[EMAIL PROTECTED]> wrote:
> Why can't I change the User's name like so:
>
> results[0].user.name = 'Brian'
> results[0].user.save()
>
> ?
>
> I instead have to assign it first:
>
> found_user = results[0].user
> found_user.name = 'Brian'
> found_user.save()
>
> Any help understanding this part of the API is greatly appreciated!

When you set up the queryset initially, it doesn't actually hit the
database yet. So your "result" variable doesn't contain any objects,
it just contains instructions on how to get the objects.

Instead, you're actually executing the query when you use results[0].
This hits the database, gathers the results into a temporary list, and
returns the first item in that list. Since you didn't assign that list
anywhere, Python (and thus, Django) has no way of knowing that it
should reuse it.

So when you use results[0] again, Django hits the database a second
time, getting you a fresh copy of the object, as it appears in the
database. That means it doesn't have the modification you made to the
first object, so when you save it, you'll notice that nothing changes
in the database.

So, in a nutshell, you're altering the name on object 1, but saving
object 2, which was never modified. Assigning results[0].user to a
variable makes sure that you're using the same object each time,
without hitting the database and getting multiple copies.

I don't know if I made that very clear, but if I didn't, I'm sure
somebody else here can explain it better. Hope this helps!

-Gul

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to