Skip to content

Commit 28118ed

Browse files
committed
refs #281, Sorting by foreign keys
Sorting for foreign keys works again. A temporary column is added that maps the fk to the description column of the parent table, the dataset is sorted on this temporary column, then the temporary column is dropped in place.
1 parent caa0754 commit 28118ed

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

pysimplesql/pysimplesql.py

+12-7
Original file line numberDiff line numberDiff line change
@@ -2206,13 +2206,15 @@ def sort_by_column(self, column: str, table: str, reverse=False) -> None:
22062206
rels = Relationship.get_relationships(table)
22072207
for rel in rels:
22082208
if column == rel.fk_column:
2209-
# change the rows used for sort criteria
2210-
rel.frm[rel.parent_table]
2211-
2212-
# change our target column to look in
2213-
2214-
# and return the value in this column
2215-
rel.frm[rel.parent_table].description_column
2209+
# Create a mapping dictionary from the parent DataFrame
2210+
df_parent = self.frm[rel.parent_table].rows
2211+
desc_parent = self.frm[rel.parent_table].description_column
2212+
mapping = dict(zip(df_parent[rel.pk_column], df_parent[desc_parent]))
2213+
2214+
# Create a temporary column in self.rows for the fk data
2215+
tmp = f"temp_{rel.parent_table}.{rel.pk_column}"
2216+
self.rows[tmp] = self.rows[rel.fk_column].map(mapping)
2217+
column = tmp
22162218
break
22172219
try:
22182220
self.rows.sort_values(
@@ -2222,6 +2224,9 @@ def sort_by_column(self, column: str, table: str, reverse=False) -> None:
22222224
)
22232225
except KeyError:
22242226
logger.debug(f"DataFrame could not sort by column {column}. KeyError.")
2227+
finally:
2228+
# Drop the temporary description column (if it exists)
2229+
self.rows.drop(columns=tmp, inplace=True, errors="ignore")
22252230

22262231
def sort_by_index(self, index: int, table: str, reverse=False):
22272232
"""

0 commit comments

Comments
 (0)