SQLAlchemy db.session.query() vs model.query -


for simple return results query should 1 method preferred on other? can find uses of both online can't find describing differences.

db.session.query([my model name]).all()  [my model name].query.all() 

i feel [my model name].query.all() more descriptive.

it hard give clear answer, there high degree of preference subjectivity in answering question.

from 1 perspective, db.session desired, because second approach requires incorporated in model added step - not there default part of base class. instance:

base = declarative_base() dbsession = scoped_session(sessionmaker()) class user(base):    __tablename__ = 'users'     id = column(integer, primary_key=true)    name = column(string)    fullname = column(string)    password = column(string) session = session() print(user.query) 

that code fails following error:

attributeerror: type object 'user' has no attribute 'query'

you need this:

class user(base):    __tablename__ = 'users'     id = column(integer, primary_key=true)    name = column(string)    fullname = column(string)    password = column(string)    query = dbsession.query_property() 

however, argued because not enabled default, doesn't invalidate reasonable way launch queries. furthermore, in flask-sqlalchemy package (which simplifies sqlalchemy integration flask web framework) done part of model class (doc). adding query property model can seen in sqlalchemy tutorial (doc):

class user(object):    query = db_session.query_property()    .... 

thus, people argue either approach.

i have preference second method when selecting single table. example:

serv = service.query.join(supplier, supplierusr).filter(supplierusr.username == usr).all() 

this because of smaller line length , still readable.

if selecting more 1 table or specifying columns, use model query method extracting information more 1 model.

deliverables = db.session.query(deliverable.column1, batchinstance.column2).\     join(batchinstance, service, supplier, supplieruser). \     filter(supplieruser.username == str(current_user)).\     order_by(deliverable.created_time.desc()).all() 

that said, counter argument made in using session.query method makes code more consistent, , when reading left right, reader knows sqlalchemy directive going read query, before mentally absorbing tables , columns involved.

at end of day, answer question subjective , there no correct answer, , code readability benefits either way tiny. thing see strong benefit not use model query if selecting many tables , instead use session.query method.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -