0

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

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)

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

谢谢!C

4

1 回答 1

2

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

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

首先,从返回行的查询开始Reading

q = session.query(Reading)

接下来,扩展查询以说明您希望点击user指向 的属性的链接User

q = q.join(Reading.user)

最后只过滤掉具有所需User特征的行。确保您根据具体的实际值进行过滤。

q = q.filter(User.emailAddress == 'alice@example.com')
于 2013-09-29T04:52:04.967 回答