SQLalchemy查询过滤器语法不起作用

时间:2013-09-29 04:40:27

标签: sqlalchemy flask

以下是我正在使用的模型:

class User(db.Model):
__tablename__ = 'user'
uid = db.Column(db.Integer, primary_key=True, index=True)
firstName = db.Column(db.String(100))
lastName = db.Column(db.String(100))
emailAddress = db.Column(db.String(120), unique=True, index=True)
pwHash = db.Column(db.String(256))
userLevel = db.Column(db.Integer())
userAccountType = db.Column(db.Integer())
isUserActive = db.Column(db.Boolean())
isUserLockedOut = db.Column(db.Boolean())
userLastLogin = db.Column(db.DateTime())
lastInvalidLogin = db.Column(db.DateTime())
userCreatedAt = db.Column(db.DateTime())
userConfirmedAt = db.Column(db.DateTime())
userUpdatedAt = db.Column(db.DateTime(), onupdate=datetime.datetime.now())
userAddress = db.relationship('Address', backref='user', lazy='dynamic')
userContactMethod = db.relationship('UserContactMethod', backref='user', lazy='dynamic')
userSensor = db.relationship('Sensor', backref='user', lazy='dynamic')
userReading = db.relationship('Reading', backref='user', lazy='dynamic')
deliveryEvents = db.relationship('logSMTPDeliveryEvents', backref='user', lazy='dynamic')

class Reading(db.Model):
    __tablename__ = 'reading'

rid = db.Column(db.Integer, primary_key=True)
uid = db.Column(db.Integer, db.ForeignKey('user.uid'))
sid = db.Column(db.Integer, db.ForeignKey('sensor.sid'))
readingTimestamp = db.Column(db.DateTime())
readingLightValue = db.Column(db.Integer)
readingLightStatus = db.Column(db.String(6))
readingTemp1 = db.Column(db.Float)
readingTemp2 = db.Column(db.Float)
readingHumidity = db.Column(db.Float)

因此,我的读数表将用户ID设置为读数表中的外键。现在,当我尝试发出这样的查询时:

queryResult = db.session.query(Reading).filter(Reading.uid == User.uid)

我得到了所有的行,这是不正确的。我该如何构建此查询?

谢谢! ç

1 个答案:

答案 0 :(得分:2)

目前尚不清楚你要从你的问题中过滤掉什么;您是否尝试查找与特定Reading行对应的User行?

假设您拥有用户的电子邮件地址,并且想要找到属于该用户的Reading,则需要分三步构建您的查询:

首先,从一个返回Reading之外的行的查询开始:

q = session.query(Reading)

接下来,展开查询,说明您想要user链接到User的属性。

q = q.join(Reading.user)

最后,只筛选出具有所需User功能的行。确保过滤具体的实际值。

q = q.filter(User.emailAddress == 'alice@example.com')