Per-transaction isolation level in Django ORM

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 17:23:46

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.postgresl',
        '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')
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!