I'm using SQLAlchemy
in Python 3 and am confused why the following code works - it looks to me like what should be an object level variable is acting as a class variable. I have seen Why is instance variable behaving like a class variable in Python? which doesn't look related to my question.
I have the following declarations in a db
module in which I create an instance of Base
and set a query
variable on it that points to the SessionFactory
query_property()
import sqlalchemy as sa
import sqlalchemy.ext.declarative as sa_ed
Base = sa_ed.declarative_base()
engine = sa.create_engine('connection string')
session_factory = session or sa_orm.scoped_session(sa_orm.sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base.query = session_factory.query_property() # make the query_property available in models for querying
My model classes are then declared as follows:
import db
class MyModel(db.Base):
id = Column(Integer)
# more model stuff
I can then run queries by accessing the query
variable as follows:
return MyModel.query.filter(MyModel.id == 22).first()
This does work, but it looks as though the query
variable exists at the class level and not at the object instance level as I am able to access it directly through the class.
What am I not understanding?