From 50920059b6109e7091ab8c1d3f5e93c4e0e745a1 Mon Sep 17 00:00:00 2001 From: phil Date: Tue, 7 May 2024 00:29:26 +0200 Subject: [PATCH] Fix get_df with no related fields --- src/gisaf/database.py | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/gisaf/database.py b/src/gisaf/database.py index 3547b2c..46c3eb7 100644 --- a/src/gisaf/database.py +++ b/src/gisaf/database.py @@ -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)