Error with Relationships: Foreign key associated with column [...] could not find table #798
-
First Check
Commit to Help
Example Code# >>> project.database.models.model1.py
from typing import Optional, TYPE_CHECKING, List
from sqlmodel import Field, SQLModel, MetaData, Relationship, ARRAY
from datetime import datetime
from pydantic import ConfigDict
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import RelationshipProperty
if TYPE_CHECKING:
from project.database.models.model2 import Table2
class Table1(SQLModel, table=True):
metadata = MetaData(schema="non-public-schema")
model_config = ConfigDict(from_attributes=True, arbitrary_types_allowed=True)
__tablename__ = "table1"
id: Optional[int] = Field(primary_key=True, default=None)
created_at: Optional[datetime] = Field(default=None)
title: Optional[str] = None
status: str = "uploaded"
processing_details: List["Table2"] = Relationship(back_populates="table1_rec")
>>> project.database.models.model2.py
from datetime import datetime
from typing import Optional, TYPE_CHECKING, List
from sqlmodel import Field, SQLModel, MetaData, Relationship
from pydantic import ConfigDict
from sqlalchemy.orm import RelationshipProperty
if TYPE_CHECKING:
from project.database.models.model1 import Table1
class Table2(SQLModel, table=True):
metadata = MetaData(schema="non-public-schema")
__tablename__ = "table2"
model_config = ConfigDict(from_attributes=True, arbitrary_types_allowed=True)
id: Optional[int] = Field(default=None, primary_key=True)
created_at: Optional[datetime] = Field(default=None)
job_start_timestamp: Optional[datetime] = None
job_end_timestamp: Optional[datetime] = None
table1_id: Optional[int] = Field(default=None, foreign_key="non-public-schema.table1.id")
table1_rec: Optional["Table1"] = Relationship(back_populates="processing_details")
>>> main.py
from sqlmodel import SQLModel
from project.database.models.model1 import Table1
from project.database.models.model2 import Table2
def create_db_and_tables(db_client):
SQLModel.metadata.create_all(db_client.engine)
def main():
db_config = ... # properly loaded config
db_client = ... # properly configured SQLAlchemy client/engine
create_db_and_tables(db_client)
with db_client.get_session() as session: # SQLModel's session
new_record = select(Table1).filter(Table1.status == "uploaded").order_by(Table1.created_at).limit(1)
res = session.exec(new_record).first() DescriptionMy models are defined in separate files, and then brought together in main.py. The relationship is supposed to be one-to-one. Running the example code results in an error:
I tried adding I realize this exception comes from SQLAlchemy, but I haven't found the answer there; maybe somebody here can help me at least understand what's going on here. Please, help. Operating SystemWindows Operating System DetailsWindows11 SQLModel Version0.0.14 Python Version3.11.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
EDIT: SQLModel.metadata.schema = "your-schema-name" BEFORE the models are imported. As an aside, I don't have a neat solution for controlling this dynamically. This blog post describes how to do it in SQLAlchemy, but ORIGINAL ANSWER: You can fix this one of two ways:
from sqlmodel import MetaData
schema_info = MetaData(schema="non-public-schema") In your model files add the line
|
Beta Was this translation helpful? Give feedback.
-
adding |
Beta Was this translation helpful? Give feedback.
EDIT:
I'm leaving the below in place for posterity, but I think the actual solution is simpler and I had some major misunderstandings when I wrote it. When you create a
MetaData
object and use it to set properties on the tables, it interferes with any calls that go viaSQLModel.metadata
, which is referencing its ownMetaData
object stored in a class variable onSQLModel
. The simplest way to set the schema is to callBEFORE the models are imported.
As an aside, I don't have a neat solution for controlling this dynamically. This blog post describes how to do it in SQLAlchemy, but
Base.metadata
seems to behave differently fromSQLModel.metadata
i…