Jeg har prøvet at bruge to databaser til at simulere din sag, og finde ud af løsningen nedenfor:
1. Scenarie:
- database
schema1
, som administreres af django (læs og skriv) - database
schema2
, hvilket er IKKE administreret af django
2. Trin:
- opret migreringer
python manage.py makemigrations
til dine modeller - Generer SQL til din migrering:
python manage.py sqlmigrate app 0001
.(antag, at det genererede migreringsfilnavn er0001_initial.py
fra trin 1 )
sql'en til denne migrering skulle se sådan ud:
CREATE TABLE `user_info` (`id_id` integer NOT NULL PRIMARY KEY, `name` varchar(20) NOT NULL);
ALTER TABLE `user_info` ADD CONSTRAINT `user_info_id_id_e8dc4652_fk_schema2.user_extra_info_id` FOREIGN KEY (`id_id`) REFERENCES `user_extra_info` (`id`);
COMMIT;
Hvis du kører ovenstående sql direkte, vil du blive ende med fejl som denne:
django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'user_extra_info'")
Det er fordi django antager, at alle dine migreringstrin udføres i den samme database . Så den kan ikke finde ud af user_extra_info
i schema1
database.
3. Følgende trin:
-
Eksplicit angiv databasen
schema2
til tabeluser_extra_info
:ALTER TABLE `user_info` ADD CONSTRAINT `user_info_id_id_e8dc4652_fk_schema2.user_extra_info_id` FOREIGN KEY (`id_id`) REFERENCES schema2.user_extra_info (`id`);
-
Kør den reviderede sql manuelt i
schema1
database. -
Fortæl django, at jeg selv har kørt migreringen:
python manage.py migrate --fake
-
Færdig!!
Kildekode Til din reference:
models.py
from django.db import models
class UserExtraInfo(models.Model):
# table in schema2, not managed by django
name = models.CharField('name', max_length=20)
class Meta:
managed = False
db_table = 'user_extra_info'
class UserInfo(models.Model):
# table in schema1, managed by django
id = models.OneToOneField(
UserExtraInfo,
on_delete=models.CASCADE,
primary_key=True
)
name = models.CharField('user name', max_length=20)
class Meta:
db_table = 'user_info'
settings.py
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'schema1',
'USER': 'USER',
'PASSWORD': 'PASSWORD',
'HOST': 'localhost',
'PORT': 3306,
},
'extra': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'schema2',
'USER': 'USER',
'PASSWORD': 'PASSWORD',
'HOST': 'localhost',
'PORT': 3306,
}
}
DATABASE_ROUTERS = ['two_schemas.router.DBRouter']
router.py
class DBRouter(object):
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth_db.
"""
if model._meta.db_table == 'user_extra_info':
# specify the db for `user_extra_info` table
return 'extra'
if model._meta.app_label == 'app':
return 'default'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth_db.
"""
if model._meta.db_table == 'user_extra_info':
# specify the db for `user_extra_info` table
return 'extra'
if model._meta.app_label == 'app':
return 'default'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Relations between objects are allowed if both objects are
in the primary/replica pool.
"""
db_list = ('default', 'extra')
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'auth_db'
database.
"""
if app_label == 'app':
return db == 'default'
return None