Python Flask SQLAlchemy 按值或另一个过滤器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40535547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask SQLAlchemy filter by value OR another
提问by Michael Yousrie
I have a Flask project that interacts with MySQL
db through Flask-SQLAlchemy
.
我有一个 Flask 项目,它MySQL
通过Flask-SQLAlchemy
.
My question is, how to select a row from the database based on a value OR another value.
我的问题是,如何根据一个值或另一个值从数据库中选择一行。
The results I want in SQL looks like this
我在 SQL 中想要的结果如下所示
SELECT id FROM users WHERE email=email OR name=name;
How to achieve that in Flask-SQLAlchemy
?
如何实现Flask-SQLAlchemy
呢?
回答by Jonathan
The following may help:
以下可能有帮助:
# app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'url_or_path/to/database'
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50), unique=True)
name = db.Column(db.String(30))
def __init__(self, name=None, email=None):
if not name:
raise ValueError('\'name\' cannot be None')
if not email:
raise ValueError('\'email\' cannot be None')
self.name = name
self.email = email
class UserQuery(object):
@staticmethod
def get_user_id_by_email_or_name(email=None, name=None):
user = User.query.filter((User.email == email) | (User.name == name)).first()
return user.id if hasattr(user, 'id') else None
The '|' can be used inside a filter instead of 'or_'. See Using OR in SQLAlchemy.
'|' 可以在过滤器中使用,而不是“or_”。请参阅在 SQLAlchemy 中使用 OR。
You can use like this:
你可以这样使用:
>>> from app import db, User, UserQuery
>>> db.create_all()
>>> user = User(name='stan', email='[email protected]')
>>> db.session.add(user)
>>> db.session.commit()
>>> by_name_id = UserQuery.get_user_id_by_email_or_name(name='stan')
>>> by_email_id = UserQuery.get_user_id_by_email_or_name(email='[email protected]')
>>> by_name_id == by_email_id
True
回答by Tri
I also needed this case today, I found this nice answer here:
我今天也需要这个案例,我在这里找到了这个很好的答案:
So, we can make ORlogic like the below example:
所以,我们可以像下面的例子一样制作OR逻辑:
from sqlalchemy import or_
db.session.query(User).filter(or_(User.email=='[email protected]', User.name=="username")).first()
When using the filter()
expression, you must use proper comparison operators, whereas filter_by()
uses a shortened unPythonic form.
使用filter()
表达式时,您必须使用适当的比较运算符,而filter_by()
使用缩短的非 Pythonic 形式。