Search code examples
djangodjango-modelsdjango-mysql

Django ForeignKey from external Database


I'm working with 2 Databases, 1 external not managed by Django and the other internal.

Thi is the external database now working on models and in Admin site:

class Client(models.Model):# IMPORT FROM MYSQL
code = models.CharField(max_length=3, primary_key=True)
name = models.CharField(max_length=250)
region_id = models.IntegerField(db_column="RegionId")

class Meta:
    managed = False
    db_table = 'client'

And this is the one managed by Django on the other DB:

class ClientJuno(models.Model):
    LABORATORIES = (('SCR','SCREENS'), ('DVR','DVMR'),)
    client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True)
    profiles = models.ManyToManyField(JunoProfile)
    laboratory = models.CharField(max_length=20, choices=LABORATORIES)

See error on opening this last model. Can't find table Client.

  OperationalError at /admin/settings/clientjules/
no such table: client
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin/settings/clientjules/
Django Version: 2.2.11
Exception Type: OperationalError
Exception Value:    
no such table: client
Exception Location: /usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 383
Python Executable:  /usr/local/bin/python
Python Version: 3.6.10
Python Path:    
['/app/mmike',
 '/usr/local/lib/python36.zip',
 '/usr/local/lib/python3.6',
 '/usr/local/lib/python3.6/lib-dynload',
 '/usr/local/lib/python3.6/site-packages']
Server time:    Mon, 20 Apr 2020 08:11:26 +0000

enter image description here


Solution

  • It seems this is not supported by Django.

    How to use django models with foreign keys in different DBs?

    Cross-database limitations Django doesn't currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database.

    Django - limitations-of-multiple-databases