Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
dingyaguang117 opened this issue Dec 21, 2019 · 6 comments
Open

Comments

@dingyaguang117
Copy link
Contributor

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
Copy link
Owner

You could use object_session for that.

@siddhantgoel
Copy link
Owner

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
Copy link
Contributor Author

dingyaguang117 commented Dec 22, 2019

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
Copy link
Owner

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
Copy link
Contributor Author

Yeah, User.query is a better way !

@arLevi
Copy link

arLevi commented Mar 8, 2023

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()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants