I'm using Django and trying to find something similar to nowait=True in Django admin page. I have some script which locks entries(select for update) during working. So, when I try to change some fields values in Django admin page for that entry when its locked, admin page waits for unlocking that entry(in my case it could take minutes). I want to raise error(something like "database entry is locked") in admin page without waiting for unlocking.
Asked
Active
Viewed 22 times
1
-
I think there is no easy way. One idea that comes to mind is configuring Django with [multiple dbs](https://docs.djangoproject.com/en/4.2/topics/db/multi-db/) where they would all point to the same actual db but [one connection is configured with short lock timeout](https://medium.com/squad-engineering/configure-postgres-statement-timeouts-from-within-django-6ce4cd33678a). And then you need to somehow [route Django admin queries](https://docs.djangoproject.com/en/4.2/topics/db/multi-db/#exposing-multiple-databases-in-django-s-admin-interface) to the short-timeout db connection. – Anentropic Aug 08 '23 at 10:20
-
You could also just set a shorter lock timeout globally, either directly in the db or in Django connection attrs to the db, and that would avoid having to wait minutes to get a lock (but of course wouldn't be the same as `nowait` immediate fail) – Anentropic Aug 08 '23 at 10:22
1 Answers
0
Have found solution. We can overwrite save_model method
class SomeDBAdmin(admin.ModelAdmin):
list_display = ('id', 'name')
@transaction.atomic
def save_model(self, request, obj, form, change):
try:
SomeDB.objects.select_for_update(nowait=True).get_or_create(id=obj.id)
except DatabaseError as e:
# if new record in db save it.
if not change:
obj.save()
print(f'exception {e}')
super().save_model(request, obj, form, change)

Goroshek
- 81
- 11
-
but with this code I've lost the ability to create new switches in admin page – Goroshek Aug 08 '23 at 10:57
-
-
Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 11 '23 at 03:22