By default, is transaction used in Django Admin Actions?
Asked Answered
R

2

1

I know that by default, transaction is used in Django Admin when adding, changing and deleting data according to my tests.

But, I selected Delete selected persons and clicked on Go in Django Admin Actions. *I use PostgreSQL:

enter image description here

Then, clicked on Yes, I'm sure to delete data:

enter image description here

Now, only one query DELETE is run without including one or more other queries between BEGIN and COMMIT as shown below so I doubt that by default, transaction is used in Django Admin Actions. *These below are the PostgreSQL query logs and you can check how to log PostgreSQL queries :

enter image description here

So by default, is transaction used in Django Admin Actions?

Ramrod answered 30/12, 2022 at 21:23 Comment(0)
R
2

No, by default, transaction is not used in Django Admin Actions.

First, you can see @transaction.atomic or with transaction.atomic(): is not used for the default delete_queryset() below:

class ModelAdmin(BaseModelAdmin):
    
    # ...

    def delete_queryset(self, request, queryset):
        """Given a queryset, delete it from the database."""
        queryset.delete()

    # ...

Second, if you add select_for_update() code to delete_queryset() by overriding it as shown below:

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):

    def delete_queryset(self, request, queryset):
        print(queryset.select_for_update()) # Here
        queryset.delete()

Then, select Delete selected persons and click on Go in Django Admin Actions:

enter image description here

Then, click on Yes, I'm sure to delete data:

enter image description here

You will get the error below because select_for_update() needs to be used with transaction so which means by default, transaction is not used in Django Admin Actions:

django.db.transaction.TransactionManagementError: select_for_update cannot be used outside of a transaction.

Ramrod answered 30/12, 2022 at 21:23 Comment(0)
A
0

If ATOMIC_REQUESTS is True (link), then by default custom actions will be executed in an atomic block.

If you want to override this, do something like this

from django.contrib import admin
from django.db import transaction

class MyModelAdmin(admin.ModelAdmin):

    @transaction.non_atomic_requests
    def changelist_view(self, *args, **kwargs):
        return super().changelist_view(*args, **kwargs)
Adore answered 20/5 at 20:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.