Open dingyaguang117 opened 4 years ago
You could use object_session
for that.
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.
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.
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.
Yeah, User.query
is a better way !
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()
like: