Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask SQLAlchemy filter by value OR another

I have a Flask project that interacts with MySQL db through 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

SELECT id FROM users WHERE email=email OR name=name;

How to achieve that in Flask-SQLAlchemy?

like image 544
Michael Yousrie Avatar asked Nov 10 '16 19:11

Michael Yousrie


2 Answers

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.

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
like image 153
Jonathan Avatar answered Sep 20 '22 19:09

Jonathan


I also needed this case today, I found the nice answer here:

So, we can make OR logic like the below example:

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.

like image 37
Tri Avatar answered Sep 20 '22 19:09

Tri