On Wed, Nov 6, 2013 at 3:28 AM, bsa <[email protected]> wrote: > After resisting ORM and database abstraction packages for a long time in > favour of plain sqlite3, I decided to give SQLAlchemy's ORM features a try. > > I've managed to specify a schema and get objects in and out of tables. I'm > not sure if I'm "doing it right" though. I feel like I have a fairly typical > use case, but that I might be writing more / uglier code than I need to. > > Given the schema below, is my insert_into_sql() function idiomatic? The > objects are passed into this function as nested dictionaries/lists after > being parsed from the attached YAML file. > > In particular: > > 1) Is this way of constructing the schema objects from dictionaries > idiomatic / clear (using the built-in constructor in Base which takes fields > as **kwargs)?
Yes, I would say this was fine. > 2) Do I need to be doing the manual "flush() + get ID" fiddling to create > the linkage between objects? Or is there a better way to do this, eg by > linking the objects together in code and making a single session call at the > end to insert all the rows in one hit? Linking the objects would be easy to do, and might make the code clearer. You would get rid of your calls to session.flush, and rather than assigning to hardware_id, tag_id and so on, you would have: hw_dict['tag'] = tag_obj # for the hardware-tag relationship hw_obj.mods.append(Mod(**m_dict)) # for the hardware-mod relationship etc. > 3) What's 'best practice' for transaction management with SQLAlchemy ORM? > The documentation provides a snippet for a context manager called > session_scope(); is there anything like that built-in that I could/should be > using? > http://docs.sqlalchemy.org/en/latest/orm/session.html It really depends on the application. For example, web applications tend to be different to traditional GUI applications, which are different again from quick scripts. > 4) Any other comments or suggestions? Sorry for the fairly open-ended > question, but I think a few tips / pointers in the right direction will go a > long way. > It looks like you've done fine so far. How you proceed from here really depends on how you application is going to use the data in this database. Cheers, Simon -- 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/groups/opt_out.
