Fix get_df with no related fields
This commit is contained in:
parent
2ea672293d
commit
50920059b6
1 changed files with 15 additions and 14 deletions
|
@ -106,20 +106,21 @@ class BaseModel(SQLModel):
|
|||
## Chamge column names to reflect the joined tables
|
||||
## Leave the first columns unchanged, as their names come straight
|
||||
## from the model's fields
|
||||
joined_columns = list(df.columns[len(cls.model_fields):])
|
||||
renames: dict[str, str] = {}
|
||||
# Match colum names with the joined tables
|
||||
# This uses the fact that orders of the joined tables
|
||||
# and their columns is preserved by sqlalchemy query options (joinedlaod),
|
||||
# and pandas' read_sql
|
||||
# Important: apparently, the order defined in cls.selectinload has to match the
|
||||
# order of the relationship fields defined in the model class definition
|
||||
for joined_table in joined_tables:
|
||||
target = joined_table.property.target # type: ignore
|
||||
for col in target.columns:
|
||||
## Pop the column from the colujmn list and make a new name
|
||||
renames[joined_columns.pop(0)] = f'{target.schema}_{target.name}_{col.name}'
|
||||
df.rename(columns=renames, inplace=True)
|
||||
if with_related:
|
||||
joined_columns = list(df.columns[len(cls.model_fields):])
|
||||
renames: dict[str, str] = {}
|
||||
# Match colum names with the joined tables
|
||||
# This uses the fact that orders of the joined tables
|
||||
# and their columns is preserved by sqlalchemy query options (joinedlaod),
|
||||
# and pandas' read_sql
|
||||
# Important: apparently, the order defined in cls.selectinload has to match the
|
||||
# order of the relationship fields defined in the model class definition
|
||||
for joined_table in joined_tables:
|
||||
target = joined_table.property.target # type: ignore
|
||||
for col in target.columns:
|
||||
## Pop the column from the colujmn list and make a new name
|
||||
renames[joined_columns.pop(0)] = f'{target.schema}_{target.name}_{col.name}'
|
||||
df.rename(columns=renames, inplace=True)
|
||||
## Finally, set the index of the df as the index of cls
|
||||
df.set_index([c.name for c in cls.__table__.primary_key.columns], # type: ignore
|
||||
inplace=True)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue