On Fri, Aug 27, 2010 at 5:07 AM, Andy <selforgani...@gmail.com> wrote:

> In this presentation save() is described as not thread-safe and
> update() is recommended to be used instead of save():
>
> http://www.slideshare.net/zeeg/db-tips-tricks-django-meetup      (page
> 2, 3, 4)
>
> Is it true that save() is not thread-safe? How is it not? Should I
> avoid using save() and use update() instead?
>

It's a matter of what your code is doing. While you can write code using
save() in a way that is not thread-safe, you do not necessarily need to
switch to update() to fix the issue. Consider code like this in a view:

            for answer in chosen_answers:
                answer.votes += 1
                answer.save()

That is not thread-safe. Running on a production web server, that block of
code may be simultaneously running to handle multiple different requests.
Incrementing the vote count in the view, based on whatever was read earlier
and may now be stale, runs the risk of losing votes. A thread-safe version
is:

            from django.db.models import F
            for answer in chosen_answers:
                answer.votes = F('votes') + 1
                answer.save()

The use of an F() expression (
http://docs.djangoproject.com/en/dev/ref/models/instances/#updating-attributes-based-on-existing-fields)
will push the responsibility for ensuring the value is atomically updated
onto the database.

(Example code taken from the book you can find by following the link in my
sig...there are more details of how to test for such issues in the book.)

Karen
-- 
http://tracey.org/kmt/

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

Reply via email to