Skip to content

Instantly share code, notes, and snippets.

@polozhevets
Created July 10, 2019 12:51
Show Gist options
  • Save polozhevets/1c0c97e7c531aeadd077d47bda7ac6cf to your computer and use it in GitHub Desktop.
Save polozhevets/1c0c97e7c531aeadd077d47bda7ac6cf to your computer and use it in GitHub Desktop.
Clone sqlalchemy model
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
@polozhevets
Copy link
Author

Its designed to return dict. U can create model in a simple way:
model = Model(**model_dict)

@shaneatendpoint
Copy link

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