~ / blog / development / set-database-tables-prefix-in-django
django 2022-08-14·1 min read

Set database tables prefix in Django

Sometimes when you using same database by different applications it is a good (or required) to separate tables between apps to avoid any conflicts. In this case you can find useful django-database-prefix library available on PyPi

shell
pip install django-database-prefix

After package installation you need to add it to the your project’s settings.py file on first place.

python
'django_database_prefix',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

Configuration

You also need to set prefix which will be used by Django to create new tables in the settings.py file.

python
DB_PREFIX = 'prefix_'

Do not forget underscore

Do not forget _ symbol at the end of prefix otherwise it will be not added to the table names.

Prefix changing

If you change DB_PREFIX setting after will be created any tables using current prefx and then need to change it - you need to manually change prefix for existing tables in the database otherwise Django will raise an error “Table does not exists”