在引用uid时创建新的SQLalchemy对象失败

时间:2013-09-14 22:14:24

标签: python mysql sqlalchemy

新的python和SQLAlchemy用户在这里(是的,我知道:))无论如何,我正在尝试使用用户,传感器和阅读表创建一些表,其中用户和传感器都与阅读有一对多的关系。 / p>

我的课程是这样的:

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)

    def __init__(self, uid, sid, readingTimestamp, readingLightValue, readingLightStatus, readingTemp1, readingTemp2,
                 readingHumidity):

        self.uid = uid
        self.sid = sid
        self.readingTimestamp = readingTimestamp
        self.readingLightValue = readingLightValue
        self.readingLightStatus = readingLightStatus
        self.readingTemp1 = readingTemp1
        self.readingTemp2 = readingTemp2
        self.readingHumidity = readingHumidity

所以,如果我尝试在这样的对象上创建:

    newReading = Reading(uid=10, sid=123,readingTimestamp = readingTimestamp, readingLightValue=readingLightValue,
                         readingLightStatus=readingLightStatus, readingTemp1=readingTemp1, readingTemp2=readingTemp2,
                         readingHumidity=readingHumidity)
    db.session.add(newReading)
    db.session.commit()

我在哪里硬编码uid一切正常。 Hoewever如果我在此之前尝试使用我的查询:

    userID = db.session.query(User.uid).filter(User.emailAddress == userEmailAddress).first()

然后我在我的创建对象中使用userID变量,如下所示:

    newReading = Reading(uid=userID, sid=123,readingTimestamp = readingTimestamp, readingLightValue=readingLightValue,
                         readingLightStatus=readingLightStatus, readingTemp1=readingTemp1, readingTemp2=readingTemp2,
                         readingHumidity=readingHumidity)

我收到以下错误:

IntegrityError: (IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`gnomecentral`.`reading`, CONSTRAINT `reading_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `user` (`uid`))') 'INSERT INTO reading (uid, sid, `readingTimestamp`, `readingLightValue`, `readingLightStatus`, `readingTemp1`, `readingTemp2`, `readingHumidity`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)' ((10L,), 123, datetime.datetime(2013, 9, 14, 14, 48, 7, 684071), 43, '43', 43.0, 43.0, 43.0)

提前感谢您的帮助! 克雷格

2 个答案:

答案 0 :(得分:0)

userID不是您正在寻找的uid,而是SQLAlchemy结果元组。这样做:

userID = db.session.query(User.uid).filter(User.emailAddress == userEmailAddress).scalar()

一些额外的事情:

  1. 如果您只是以这种方式使用Reading.__init__方法,则db.Model.__init__方法已经相同:

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattribute(self, key, value)
    
  2. 如果用户 - >阅读是一对多的关系,userReading不会userReadings更清晰?

  3. Python中的一个常见惯例是将变量,方法和函数命名为like_this而不是camelCased。

答案 1 :(得分:0)

.first()返回一行包含单个值,而不是单个值。因此,您尝试将一组值用作新对象中的uid。你可以在错误中看到这个;有一个元组应该是一个元组。

您可以使用.scalar()来获取第一行中的第一列,而不是.first()。