Skip to content

Commit 30ed3fa

Browse files
committed
Add preserve_pkey argument which allows user to specify primary key for tables which do not auto populate.
1 parent 32897bc commit 30ed3fa

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/odm2datamodels/base.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,14 +105,32 @@ def read_query(self,
105105
return df.to_dict()
106106
raise TypeError("Unknown output format")
107107

108-
def create_object(self, obj:object) -> Union[int, str]:
109-
pkey_name = obj.get_pkey_name()
110-
setattr(obj, pkey_name, None)
111108
def insert_query(self, objs:List[object]) -> None:
112109
with self.session_maker() as session:
113110
session.add_all(objs)
114111
session.commit()
115112

113+
def create_object(self, obj:object, preserve_pkey:bool=False) -> Union[int, str]:
114+
""" Accepts an ORM mapped model and created a corresponding database record
115+
116+
Accepts on one of the ORM mapped models and creates the corresponding database
117+
record, returning the primary key of the newly created record.
118+
119+
Arguments:
120+
obj:object - The ORM mapped model
121+
preserve_pkey:bool - Default=False - flag indicating if the primary key for
122+
the object should be preserved. Avoid in general use cases where database has
123+
a serial that auto assigned primary key, however this can be set to True to
124+
specify you own the primary key value.
125+
126+
Returns:
127+
primary key: Union[int, str]
128+
129+
"""
130+
131+
if not perserve_pkey:
132+
pkey_name = obj.get_pkey_name()
133+
setattr(obj, pkey_name, None)
116134

117135
with self.session_maker() as session:
118136
session.add(obj)

0 commit comments

Comments
 (0)