Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

python - Per-transaction isolation level in Django ORM

Is it possible to set isolation level for custom transaction (but not with raw sql)?

For example, something like:

with transaction.commit_on_success(isolation='SERIALIZABLE'):
    bla
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As far as I know, there's no way to temporarily change the transaction isolation level in Django for an existing database connection(s).

However, you could setup another database connection(s) that mirrors your default database connection(s) but sets the transaction isolation level.

E.g. in your settings.py:

    DATABASES = {
        'default': {
            'NAME': 'app_data',
            'ENGINE': 'django.db.backends.postgresql',
            'USER': 'postgres_user',
            'PASSWORD': 's3krit',
        },
        'serializable': {
            'NAME': 'app_data',
            'ENGINE': 'django.db.backends.postgresql',
            'USER': 'postgres_user',
            'PASSWORD': 's3krit',
            'OPTIONS': {
                'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE,
            },
        },
    }

To use the serializable transaction level, you could:

  1. Use the using() QuerySet method e.g. User.objects.using('serializable').all

  2. Add a custom manager that specifies the database connection with the transaction isolation level

    class SerializableUserManager(models.Manager):
        def get_queryset(self):
            return super(SerializableUserManager, self).get_queryset().using('serializable')
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...