Is there any method in django to use database with

2019-06-04 19:07发布

I am having a database with some data filled in it and i want to use it in my new django app. So is their any way to use data of database in my django app.Actually i don't want to make any changes in my old database and only want to use its data. Anybody please suggest me what will be the better approach to do this.

While serching i also found a command-inspectdb which can generate model.py file from database, but their are some issues with it that it does'nt map the foreign key in model.py, we need to rearrange our classes in model.py file and some more. So i am searching for some other alternative.

1条回答
聊天终结者
2楼-- · 2019-06-04 19:38

You could access data from legacy database using connection.cursor() from django.db module.

If you have two dabases

DATABASES = {
    'default': {
        'NAME': 'new_database',
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'USER': '',
        'PASSWORD': ''
    },
    'old': {
        'NAME': 'old_database',
        'ENGINE': 'django.db.backends.mysql',
        'USER': '',
        'PASSWORD': ''
    }
}

...

from django.db import connections
cursor = connections['old'].cursor()
cursor.execute("SELECT...")
cursor.fetchall()

refer to docs:

Executing custom SQL directly

Multiple databases

But if you want to modify data in your old database it is better idea to create models.py file and use it as always. Using inspectdb or not is up to you. For example you cold generate model using inpsectdb in separate temporary project, make dumpdata to create json files and upload data to your active project somehow.

查看更多
登录 后发表回答