sqlalchemy过滤来自其他关系表的数据

时间:2017-09-09 14:58:31

标签: sqlalchemy python-3.6

我有用户表:

class User(db.Model):
    __tablename__ = "users"

    UserID = db.Column(db.Integer, primary_key=True, autoincrement=True)
    FirstName = db.Column(db.String(255), nullable=False)
    # relationships
    Emails = db.relationship('Email', backref='user', lazy='dynamic')

使用电子邮件表:

class Email(db.Model):
    __tablename__ = "user_emails"

    Email = db.Column(db.String(255), unique=True, primary_key=True, nullable=False)
    UserID = db.Column(db.Integer, db.ForeignKey('users.UserID'), nullable=False)

如何根据电子邮件过滤或查找用户?

我在下面试过,但它不起作用:

DBModel.query.filter(DBModel.Emails.any(Email=searchInput))
DBModel.query.filter_by(Emails=searchInput).first()

1 个答案:

答案 0 :(得分:0)

我用这个来解决:

DBModel.query.join(DBModel.Emails).filter_by(Email=id).first()