Does ``QuerySet.select_for_update`` lock related (joined) rows as well?

523 views
Skip to first unread message

Yo-Yo Ma

unread,
Sep 4, 2012, 8:45:09 PM9/4/12
to django...@googlegroups.com
restaurant = Restaurant.objects.select_for_update().select_related('owner').get(name=u'Koala Kafe')

Assuming the ``owner`` field points to a ``Person`` table, will the aforementioned query prevent the ``Person`` row returned for the Koala Kafe's owner from being saved in a separate transaction?

(I will be using Postgres and using ``transaction.commit_on_success``)

Tom Evans

unread,
Sep 5, 2012, 6:02:01 AM9/5/12
to django...@googlegroups.com
select_for_update() …

"Returns a queryset that will lock rows until the end of the
transaction, generating a SELECT ... FOR UPDATE SQL statement on
supported databases."

Postgresql handles this …

"If specific tables are named in FOR UPDATE or FOR SHARE, then only
rows coming from those tables are locked; any other tables used in the
SELECT are simply read as usual. A FOR UPDATE or FOR SHARE clause
without a table list affects all tables used in the statement. If FOR
UPDATE or FOR SHARE is applied to a view or sub-query, it affects all
tables used in the view or sub-query."

http://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-FOR-UPDATE-SHARE

Django doesn't specify any tables when it generates a SELECT … FOR UPDATE query:

https://github.com/django/django/blob/master/django/db/backends/__init__.py#L585

Hope that helps

Tom

Yo-Yo Ma

unread,
Sep 5, 2012, 9:15:10 AM9/5/12
to django...@googlegroups.com, teva...@googlemail.com
Thanks, Tom. That does help.
Reply all
Reply to author
Forward
0 new messages