简体   繁体   中英

Django - Multiple Databases

So I'm somewhat new to the whole Django databases and maybe I just don't fully understand the Django routers talked about here: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#database-routers but for the life of me I cant figure out how to link two databases together. Maybe it's because my set-up is different? The two databases are separate Django project folders and both have separate Postgre databases. I think that maybe the problem comes form them being in different folders and I'm not including the path names properly?

Here's what I have now:

settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', 
        'NAME': 'ClothesWashers',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
        },
    'RECS': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'RECS',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
        }
}

and

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django_extensions',
    'ClothesWasher_Purchaser',
    )

and

DATABASE_ROUTERS = ['ClothesWashers.db_routers.RECS_Router',]

db_routers.py:

class RECS_Router(object):
    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'RECS_Data':
            return 'RECS'
        return 'default'

All I want to be able to do is call the RECS_Data app in the RECS database by doing something like this so that I can read from it:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'ClothesWashers.settings'
from RECS_Data.models import RecsData
g = RecsData._meta.fields

Thank you anyone who would be willing to help me!

I guess you can read a secondary database with using.

Try like this.

i.e RecsData.using("RECS")._meta.fields

For more refer here https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM