In one of my project I came across the requirement of joining two tables from different databases in Django and couldn't figure out optimal solution yet. The problem is I have two databases with tables that are correlated with each other and I want to make a join between tables of two different databases. SQL query works fine inside MS SQL Server but how to do that in Django is the main issue. I want to run the RawSQL Query inside Django and pass it to ORM. For a single database it is fine but for two databases it is not working.
For example, I have two Databases Like DB1 with table CashAccount and DB2 with table teamAccount.
SQL Query:
SELECT (t1.unique_name) as unique_name,
(t1.AccountBalanceAmount) AS AccountBalanceAmount,
(t2.TeamName) AS TeamName,
(t2.ProjectDesc) AS ProjectDesc,
FROM (
SELECT CONCAT(ID,'_',ProjectName) AS unique_name,
AccountBalanceAmount
FROM DB1.CashAccount
) t1
INNER JOIN (
SELECT CONCAT(ID,'_',ProjectName) AS unique_name,
TeamName
ProjectDesc
FROM DB2.TeamAccount
) t2 ON t1.unique_name = t2.unique_name
How do I execute this query using Django ORM or raw SQL Query using raw()?