python - Flask SQLAlchemy filter by value OR another -
i have flask project interacts mysql db through flask-sqlalchemy.
my question is, how select row database based on value or value.
the results want in sql looks this
select id users email=email or name=name;
how achieve in flask-sqlalchemy?
the following may help:
# app.py flask import flask 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 none') if not email: raise valueerror('\'email\' cannot 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 used inside filter instead of 'or_'. see using or in sqlalchemy.
you can use this:
>>> app import db, user, userquery >>> db.create_all() >>> user = user(name='stan', email='stan@email.com') >>> 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='stan@email.com') >>> by_name_id == by_email_id true
Comments
Post a Comment