Skip to content

Instantly share code, notes, and snippets.

@gavinwahl
Created August 5, 2015 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavinwahl/58fd2f8e058779527a0a to your computer and use it in GitHub Desktop.
Save gavinwahl/58fd2f8e058779527a0a to your computer and use it in GitHub Desktop.
def sa_to_django(model, row, table=None):
"""
Constructs a Django model from a sqlalchemy result row. We could just fetch
the django model by id, but that'd several queries for each row of the
report.
XXX: Does not handle _meta.state.adding (maybe it should?), so don't try to
save the model.
"""
if table is None:
table = bridge[model]
if row[table.c.id] is None:
return None
attrs = {}
for field in model._meta.fields:
attrs[field.attname] = row[getattr(table.c, field.attname)]
if isinstance(field, models.ForeignKey):
# hydrate the sub-object
try:
attrs[field.name] = sa_to_django(field.rel.to, row)
# Django won't let us pass the object (ie `sport`) and the id
# column (ie `sport_id`).
del attrs[field.attname]
except sa.exc.NoSuchColumnError:
# The pk of the sub-object wasn't selected, must not care about
# it. Django's lazy-loading will actually work if it's accessed
# later, but will use many queries.
pass
return model(**attrs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment