Thanks Jonathan,

I agree with you, 100%. I have methods for that also, when I have to deal with the real objects and queries and stuff.

The point, in my question, is that I have some services that are not vital to my application, but are used constantly -- and it just spits out data. I'm just trying to work on some edges that might help me (saving memory, I/O, etc). I can even put a plain old select :)

This question is, kind of, general and not specific to JSON, in my point of view.


best regards,
richard.

On 06/01/2015 01:28 PM, Jonathan Vanasco wrote:
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 sqlalchemy+unsubscr...@googlegroups.com <mailto:sqlalchemy+unsubscr...@googlegroups.com>. To post to this group, send email to sqlalchemy@googlegroups.com <mailto:sqlalchemy@googlegroups.com>.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

--
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 sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

<<attachment: richard.vcf>>

Reply via email to