开发者

SQLAlchemy - loading user by username

Just diving into pylons here, and am trying to get my head around the basics of SQLALchemy. I have figured out how to load a record by id:

user_q = session.query(model.User)
user = user_q.get(user_id)

But how do I query by a specific field (i.e. username)? I assume there is a quick way to do it with the model rather than hand-building the query. I think it has something with the add_column() function on the query object, but I can't quite figure out how to use it. I've been trying stuff like this, but 开发者_高级运维obviously it doesn't work:

user_q = meta.Session.query(model.User).add_column('username'=user_name)
user = user_q.get()


I believe you want something like this:

user = meta.Session.query(model.User).filter_by(name=user_name).first()

Which is short for this:

user = meta.Session.query(model.User).filter(model.User.name=user_name).first()

Here's more documentation

If you change first() into one() it will raise an exception if there isn't a user (if you want to assert one exists).

I highly suggest reading through both Object Relational Tutorial as well as the and the SQL Expression Language Tutorial.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜