siddhantgoel / tornado-sqlalchemy

SQLAlchemy support for Tornado
https://tornado-sqlalchemy.readthedocs.io/en/latest/
MIT License
125 stars 21 forks source link

A convenient way to get a session from a member method of Model #86

Open dingyaguang117 opened 4 years ago

dingyaguang117 commented 4 years ago

like:

class User(Base):
    __tablename__ = 'users'

    id = Column(BigInteger, primary_key=True)
    username = Column(String(64), unique=True)

    def __init__(self, username):
        self.username = username

    @classmethod
    def get_jack(cls):
        return cls.session.query(cls).filter(cls.name=='jack').first()
siddhantgoel commented 4 years ago

You could use object_session for that.

siddhantgoel commented 4 years ago

In general, I'm not in favor of having a session accessor in all model classes. Something like User.query might be worth thinking about, though.

dingyaguang117 commented 4 years ago

You could use object_session for that.

object_session only works for instance of Model. and the instance has already been attached to a session.

siddhantgoel commented 4 years ago

True, my bad. Providing a session accessor in model classes still seems a bit odd though. This would mean that in theory, something like User.session.query(OtherModel) is possible, which I'd like to avoid, possibly by a User.query method.

dingyaguang117 commented 4 years ago

Yeah, User.query is a better way !

arLevi commented 1 year ago

I usually separate the modal ( where i define tables ) from the view ( where i make functions to query common things )

So in Tornado, every "page" has its own class, so i do this:

from tornado_sqlalchemy import SessionMixin
from mymodals                  import User

class MyPage(SessionMixin, tornado.web.RequestHandler):
   def __init_(self):
      ...

   async def get(self, query_string_user):
        user = await self.get_user(query_string_user)        
        self.render(user)

   def get_user(self, username):
      """
      self.session magically exists because this class inherit from SessionMixin
      """
      return self.session.query(User).filter(User.name==username).first()