Skip to content

Instantly share code, notes, and snippets.

Last active February 9, 2023 18:01
What would you like to do?
Django Custom Model ForeignKey Field for Spanning Databases
Copy link

I'm trying to use this class to allow for a lookup of a user in auth_user in a 'default' DB , different from my application DB. ('test2' here).
the table I created looks like:

CREATE TABLE IF NOT EXISTS "test2_m1" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "description" text NOT NULL, "user_id" integer NOT NULL ); -- no foreign key

But when I run these statements, Django generates the following query wth an INNER JOIN to auth_user, and SpanningForeignKey.validate() is not called at all (I added a debug line to test):

from test2.models import *
M1.objects.get(user__username = 'xyz')
db_for_read: test2 ---> test2
ZZZZ SELECT "test2_m1"."id", "test2_m1"."user_id", "test2_m1"."description" FROM "test2_m1" INNER JOIN "auth_user" ON ("test2_m1"."user_id" = "auth_user"."id") WHERE "auth_user"."username" = xyz

The problem here is that the underlying Django code still wants to form a query with an INNER JOIN on the app-specific DB, not the default DB, expecting "auth_user" to be in that DB.

My questions:

  1. How do I get Django to NOT do that INNER JOIN on "auth_user" , especially when I specified no foreign key in the app's DB ? Shouldn't the SpanningForeignKey class prevent this from happening ?
  2. If SpanningForeignKey.validate() won't do that for me, what other method(s) must I override ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment