简体   繁体   中英

Multiple Databases in Django

I've 2 DB in my one Django app. The two DB's are on the same network, ie on LAN. So, I suppose the HOST IP will be different. Wouldnt it be?

As of right now, to test my code, I've provided same HOST but different PORT.

So, my DB settings are as follow:-

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'vms_db',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '127.0.0.1',
        'PORT': '8000',         
    },
    'users': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'aramex_vms_db',              
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '127.0.0.1',                  
        'PORT': '8080',                      
    }
}

When I syncdb it, it returns an error saying:-

django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)")

But when I use the same port, it works fine but the tables are made in default DB. I know the migrate command by default works on default DB.

1) But what if I want that there should be different tables for default and different for users, how will I do that?

If you want to migrate your database users:

$ ./manage.py migrate --database=users

As you can see here: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#synchronizing-your-databases

If you want to select your database while you retrieve an entry:

#default dabatase
Author.objects.all()

#custom database
Author.objects.using('DATABASE_NAME').all()

Further information: 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