Default arguments and SQL queries in Python - idioms / patterns? Default arguments and SQL queries in Python - idioms / patterns? sqlite sqlite

Default arguments and SQL queries in Python - idioms / patterns?


Unfortunately the comment system is not good for posting an example, but SQLAlchemy has a pretty much 1:1 mapping to raw SQL, and I find this approach better than composing statements from string manipulation. So this is more a comment than an answer, I hope you forgive me.

Rewriting your function ORM style would result something like:

def get_notes(self, pcb_serial_no, note_type=None):    ''' Get notes recorded against a PCB unit, optionally         filtered by note_type. '''    q = sql.select([            pcb_notes_view.pcb_serial_no,             pcb_notes_view.note_type,             pcb_notes_view.description,             pcb_notes_view.username,             pcb_notes_view.note_time        ]).where(            pcb_notes_view.pcb_serial_no==pcb_serial_no        )    if note_type is not None:        q = q.where(pcb_notes_view.note_type==note_type)    rows = q.execute().fetch_all()    return len(rows) > 0 and rows

Since the ORM makes reusing queries so easy, and the ORM can guess the relationship between tables (for databases with referential integrity), I tend to define ORM queries instead of views (mapping views from SQLSoup requires a bit more work). Combined with smart auto-complete from a good IDE (I use PyCharm) and I'm totally more productive with the ORM.

But it is a matter of taste. One could as well move all the logic to the database using stored procedures.