coleifer / peewee

a small, expressive orm -- supports postgresql, mysql, sqlite and cockroachdb
http://docs.peewee-orm.com/
MIT License
11.06k stars 1.37k forks source link

Joining From Different Database throwing an error #2911

Closed JenuelDev closed 2 months ago

JenuelDev commented 2 months ago

Example for model 1

from peewee import Model, MySQLDatabase
import os
from peewee import *

MySqlDb = MySQLDatabase(
    database=os.getenv("DB_DATABASE_ONE"),
    user=os.getenv("DB_USERNAME"),
    password=os.getenv("DB_PASSWORD"),
    host=os.getenv("DB_HOST"),
    port=int(os.getenv("DB_PORT")),
)

class BaseModelOne(Model):
    class Meta:
        database = MySqlDb

class SampleTable(BaseModelOne):
    id= PrimaryKeyField()
    detail= TextField()
    account_id = IntegerField()

    class Meta:
        table_name = "samepl_table"

example model 2

from peewee import Model, MySQLDatabase
import os
from peewee import *

MySqlDb = MySQLDatabase(
    database=os.getenv("DB_DATABASE_TWO"),
    user=os.getenv("DB_USERNAME"),
    password=os.getenv("DB_PASSWORD"),
    host=os.getenv("DB_HOST"),
    port=int(os.getenv("DB_PORT")),
)

class BaseModelTwo(Model):
    class Meta:
        database = MySqlDb

class Account(BaseModelOne):
    id= PrimaryKeyField()
    email = TextField()

    class Meta:
        table_name = "account"

But when I do this, I am getting error:

SampleTable.select(
        SampleTable.account_ID,
        Account.email
    )
    .join(
        Account,
        on=(Account.id == SampleTable.account_id ),
        join_type=JOIN.LEFT_OUTER,
    )
    .limit(1)
    .namedtuples()

But it is throwing error like:

 ProgrammingError: (1146, "Table 'db1.account' doesn't exist")

although based on the model the account is connected to db 2

coleifer commented 2 months ago

To work with multiple databases on the same MySQL server, use the schema attribute, e.g.:

class A(Model):
    class Meta:
        schema = 'db1'

class B(Model):
    class Meta:
        schema = 'db2'

This provides the additional layer of namespacing.