[Django]-How to make two django projects share the same database

19👍

You can simply define the same database in DATABASES in your settings.py. So, if your database is PostgreSQL, you could do something like this:

# in project_1/settings.py

DATABASES = {
    'default': {
        'NAME': 'common_db',
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'project_1_user',
        'PASSWORD': 'strong_password_1'
    },
}

# in project_2/settings.py

DATABASES = {
    'default': {
        'NAME': 'common_db',
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'project_2_user',
        'PASSWORD': 'strong_password_2'
    },
}

Note that both database users (project_1_user and project_2_user) should have the appropriate privileges on the database you wish to use. Or you could instead use the same user for both projects.

If you want to have more than just one database per project, you should take a look at the docs for multiple databases.

On another matter, since you share data, I guess you share functionalities as well. So for example, if project_1_app1 and project_2_app1 do same (or similar) things, it seems they could instead be a single reusable app.

Edit

Since you use sqlite3, you should ensure the path you use is the same. So, assuming that project_1 and project_2 are siblings, like so:

projects
  project_1
    settings.py
    ...
  project_2
    settings.py
    ...

you should try this:

# project_1/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(PROJECT_ROOT, 'development.db'),
    },
}


# project_2/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(
            os.path.dirname(os.path.dirname(PROJECT_ROOT)),
            'project_1',
            'development.db'
        ),
    },
}

This would give the structure you ask for. Note however that the projects are not both “standalone”. project_2 is clearly dependent on project_1‘s database.

In any case, perhaps, you should also take a look at the os.path module for more info.

4👍

You just need to declare in your model in class meta the attribute db_table with a name diferent the name of app + model (Which are automatically generated by Django) the twice projects need the same models. before the run makemigrations and migrate.

class MyModel(models.Model):
    class Meta:
        db_table = 'MyModel'

Leave a comment