8

I'm using multiple databases in a Django app. The default database is the one Django creates for user authentication, etc. Then I have a vo database, with existing data, which I plan to use for the content generation.

I wanted the classes in models.py to link up to the existing tables in vo. However, when I do

manage.py syncdb --database=vo

a set of new empty tables are created. BTW, it's a SQLite3 database.

How does one link existing tables in a database to the classes on models.py in Django?

Many thanks.

3
  • Do you want actual linking where changes in vo are reflected in queries, or is it enough to copy vo into default once? Commented Sep 6, 2014 at 6:06
  • Do you want to make a ForeignKey with multiple databases ? Commented Sep 6, 2014 at 14:14
  • It was actually enough just mirroring db into models.py. This was achieved with the answer below. Also, no need for ForeignKey. Thanks. Commented Sep 6, 2014 at 15:43

1 Answer 1

21
  1. You need to add your db vo to settings.

if you have your database settings like this

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', 
        'NAME': os.path.join(DIR, 'django.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    },
}

Add vo database settings to it like this

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', 
        'NAME': os.path.join(DIR, 'django.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    },

    # this your existing db 
    'vo': { 
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(DIR, 'vo.sqlite'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    },
}
  1. Then you can generate models automatically from the database.

    $ ./manage.py inspectdb --database=vo > your_app/models.py
    
  2. Configure database routers.

Check out: Using Django's Multiple Database Support

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, this worked. Now I just have to edit and refine the models.py it generated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.