All my models inherit from an additional base class with this method:
def columns_as_dict(self):
"""return a dict of the columns; does not handle relationships"""
return dict((col.name, getattr(self, col.name)) for col in
sqlalchemy_orm.class_mapper(self.__class__).mapped_table.c)
so when returning a JSON array, I just do something like;
return [i.columns_as_dict() for i in results]
I prefer this for several reasons:
- I don't think (anymore) that sqlalchemy should return raw data. I'm not
fine with it's internal constructs after "departing from the recommended
usage" a few times and finding myself creating more problems than I solved.
- I easily can override columns_as_dict() on classes to define only those
columns that I want returned.
- IIRC, The result_proxy/row_proxy aren't always fetched from the database,
there could still be data on the connection - or you could be on an
unloaded lazy-loaded relation. Running a list comprehension lets me slurp
all that data, and close up the DB resources sooner. This has made
pinpointing bugs a lot easier than having unloaded data accessed in a
template (which often produces hard-to-figure out tracebacks as the db is
nestled in the template, which is nestled in your app).
There are probably a dozen better reasons for why I prefer this method ,
these just popped up in my head.
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.