61👍
✅
Just call get
, slice it, etc. and save as usual. The lock is in place through the transaction.
ob = MyModel.objects.select_for_update().get(pk=1)
Any changes are committed at the end of the transaction (which by default through 1.5 is per-request)
46👍
You can also use select_for_update
with get_object_or_404
function:
from django.db import transaction
from django.shortcuts import get_object_or_404
with transaction.atomic():
obj = get_object_or_404(MyModel.objects.select_for_update(), pk=pk)
# do some stuff with locked obj
- [Django]-What is a "slug" in Django?
- [Django]-Error: [ngModel:datefmt] Expected `2015-05-29T19:06:16.693209Z` to be a date – Angular
- [Django]-How to add Check Constraints for Django Model fields?
1👍
Just after select_for_update().filter()
, you can put .first() which returns the 1st object of a queryset to update it with save() as shown below. *You can see my question and answer explaining more about select_for_update()
in Django:
# Here
ob = MyModel.objects.select_for_update().filter(some conditions).first()
ob.field_1 = 'some value'
ob.save()
- [Django]-Django – what is the difference between render(), render_to_response() and direct_to_template()?
- [Django]-WSGI vs uWSGi with Nginx
- [Django]-OneToOneField and Deleting
Source:stackexchange.com