我有一个Flask项目,通过Flask-sqlAlchemy与MySQL数据库交互.
我的问题是,如何根据值或其他值从数据库中选择一行.
我在sql中想要的结果看起来像这样
SELECT id FROM users WHERE email=email OR name=name;
如何在Flask-sqlAlchemy中实现这一目标?
最佳答案
以下可能有所帮助:
原文链接:https://www.f2er.com/mysql/433938.html# 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
‘|’可以在过滤器内使用而不是’or_’.见Using OR in SQLAlchemy.
你可以像这样使用:
>>> from 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