首先配置到setting中
'mytestdb': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'testdb',
'USER': 'test',
'PASSWORD': 'test',
'HOST': '1.1.1.1',
'PORT': 3306,
'OPTIONS': {
'init_command': 'SET default_storage_engine=INNODB;',
},
}
然后根据数据库配置,导出建表信息为django的model信息,将该信息编写到对应的model中
(python36) [root@xxxx]# python manage.py inspectdb --database mytestdb
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from __future__ import unicode_literals
from django.db import models
class testtab(models.Model):
id = models.AutoField(primary_key=True)
age = models.IntegerField()
class Meta:
managed = False
db_table = 'testtab'
Viewset 中使用
queryset = testtab.objects.all().using("mytestdb")
直接连库使用
testtabfilter = testtab.objects.filter(age=18).using('mytestdb')