Created
July 10, 2019 12:51
-
-
Save polozhevets/1c0c97e7c531aeadd077d47bda7ac6cf to your computer and use it in GitHub Desktop.
Clone sqlalchemy model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def clone_model(model): | |
"""Clone an arbitrary sqlalchemy model object without its primary key values.""" | |
# Ensure the model’s data is loaded before copying. | |
model.id | |
table = model.__table__ | |
non_pk_columns = [k for k in table.columns.keys() if k not in table.primary_key] | |
data = {c: getattr(model, c) for c in non_pk_columns} | |
data.pop('id') | |
return data |
Its designed to return dict. U can create model in a simple way:
model = Model(**model_dict)
you also don't need to pop('id')
if you have the k not in table.primary_key
list-comprehension predicate on line 7
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It returns a dict. How do I convert back to model object?