Skip to content

Commit 04afc8f

Browse files
committed
Add ModelBase.from_prepended_mapping
1 parent 3ffa0d3 commit 04afc8f

2 files changed

Lines changed: 14 additions & 0 deletions

File tree

sql_athame/dataclasses.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,16 @@ def from_mapping(cls: type[T], mapping: Mapping[str, Any], /) -> T:
313313
cls.from_mapping = from_mapping_fn # type: ignore
314314
return from_mapping_fn(mapping)
315315

316+
@classmethod
317+
def from_prepended_mapping(
318+
cls: type[T], mapping: Mapping[str, Any], prepend: str
319+
) -> T:
320+
filtered_dict: dict[str, Any] = {}
321+
for k, v in mapping.items():
322+
if k.startswith(prepend):
323+
filtered_dict[k[len(prepend) :]] = v
324+
return cls.from_mapping(filtered_dict)
325+
316326
@classmethod
317327
def ensure_model(cls: type[T], row: Union[T, Mapping[str, Any]]) -> T:
318328
if isinstance(row, cls):

tests/test_dataclasses.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,3 +210,7 @@ class Test(ModelBase, table_name="table"):
210210
assert Test.from_mapping({"foo": "FOO", "bar": "BAR"}) == Test("foo", "BAR")
211211
# make sure the monkey patching didn't screw things up
212212
assert Test.from_mapping({"foo": "FOO", "bar": "BAR"}) == Test("foo", "BAR")
213+
214+
assert Test.from_prepended_mapping(
215+
{"p_foo": "FOO", "p_bar": "BAR", "foo": "not foo", "other": "other"}, "p_"
216+
) == Test("foo", "BAR")

0 commit comments

Comments
 (0)