简体   繁体   中英

How to connect Django to external DB without migrations

I would like to connect my DjangoApp to an external MySQL database. I don't want to make migrations to this table, I mean I don't want to create new tables ,just pull data. And my question is - how to do this ? If i add this table to DATABASES in my settings file then the console shows an error about mandatory migration.

What can you recommend me ? Thanks in advance,

You can connect to that db through DATABASES settings. Actually migrations error is a warning only. You can do by managed to False .

class MyModel(models.Model):
    field1 = models.CharField()
    ...
    class Meta:
        managed = False

More info

you can connect to the external database with this

settings.configure(
DATABASE_ENGINE = 'mysql',
DATABASE_NAME = 'db_name',
DATABASE_USER = 'db_user',
DATABASE_PASSWORD = 'db_pass',
DATABASE_HOST = 'http://YourDataBaseAdress.com/mydatabase',
DATABASE_PORT = '6676',
TIME_ZONE = 'America/Sao_Paulo',) //if you want to connect this forever add this
'CONN_MAX_AGE': None,

and with for no migration you can do

class Meta:
    managed = False

in your specific model.

for pulling data from external databases you can see here

I would recommend using two databases in this case. The fist can use the standard sqllite db, and will be used for storing login data and admin related stuff.

If you want to create the class definitions for the legacy database you can use python manage.py inspectdb > mysql_models.txt . This will also add managed = False to your model class meta and make django shut up about missing migrations.

The mandatory migrations warning is what is is: A warning. You don't have to apply the migrations.

Docs: https://docs.djangoproject.com/en/1.11/topics/db/multi-db/

A kind warning before you start using the legacy database: Check if it is compliant with the django orm. There are some database features (like compound primary keys) that will not work with the django orm.

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