Multiple databases relationships

Hi,
let’s say I have tow databases: (db.sqlite3 and measure.db.sqlite3)

I am using routers to manipulate those databases so my question is how to set a ForeignKey from a measure.db and SurveillanceDesPuits table to another table in db,
in the first db I have this table

class Wellinfo(models.Model):
    WellID    = models.CharField(max_length=15,unique=True)
    def __str__(self):
        return self.WellID

and in the second database I have this table :

class SurveillanceDesPuits (models.Model):
    WellID    = models.CharField(max_length=15,unique=True)  # this field is related to the old database and table 
     fields      =  models.CharField(max_length=15)
    def __str__(self):
        return self.WellID

knowing that my routers.py is configured as:

from os import read
class AuthRouter:
    route_app_labels = {'auth', 'contenttypes','sessions','admin','Home','user'}

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'default'
        return None
    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'default'
        return None
    
    def allow_relation(self, obj1, obj2, **hints):
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
            return True
        return None
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == 'default'
        return None


class Measure:
    route_app_labels = {'measure'}
    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'measure_db'
        return None
    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'measure_db'
        return None
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == 'measure_db'
        return None

Hi again I tried this solution so,
in the second database I imported the table Wellinfo (the app is Home)

from Home.models import Wellinfo

class SurveillanceDesPuits(models.Model):
    WellID    =  models.ForeignKey(Wellinfo ,to_field='WellID', on_delete=models.CASCADE)
    fields      =  models.CharField(max_length=15)

after migrations, I opened the admin panel and it works I found the tables;

and I tried to added a data as :


so here it imports the list of wells from the old DB and when I save it shows me this error!

django.db.utils.OperationalError: no such table: main.Home_wellinfo
[05/Sep/2021 11:03:31] "POST /admin/measure/surveillancedespuits/add/ HTTP/1.1" 500 208017

what I missed here?

Did you read the section of the docs on Limitations of multiple databases?

1 Like