修改SQLAlchemy对象中的现有值

时间:2014-07-17 08:45:58

标签: python sqlalchemy

我正在尝试在检索到的SQLAlchemy对象中获取现有字符串,并将其与第二个字符串连接,但是没有写入任何值。

print(messages)
testsuite = session.query(Testsuite).get(test_id)
testsuite.console += messages
session.commit()

检查数据库时,记录保持原来的空值 - messages从未添加过。

我的Testsuite模型如下:

# Represents schema - used by engine to create tables etc.
Base = declarative_base()


# These SQL fields are horrendously inefficient - need replacing ASAP!
class Testsuite(Base):
    """Testsuite model to map testsuite in progress to SQL DB."""

    __tablename__ = 'testsuites'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    timestamp = Column(DateTime, default=datetime.datetime.utcnow)
    product_name = Column(String)
    serial_number = Column(String)
    total_tests = Column(Integer)
    completed_tests = Column(Integer)
    console = Column(Text)
    report_id = Column(Integer)
    testcases = relationship('Testcase', backref='testsuite')
    result = Column(String)

    def __init__(self, testsuite_name, product_name, serial_number, total_tests=0):
        self.name = testsuite_name
        self.product_name = product_name
        self.serial_number = serial_number
        self.total_tests = total_tests
        self.completed_tests = 0
        self.result = 'pending'

我读过我修改物体的方式会导致竞争条件,但我不确定是否有合适的选择。任何人都可以指出我正在做的事情以及为什么没有添加messages字符串的问题吗?

谢谢:)

1 个答案:

答案 0 :(得分:1)

经过一些实验后,似乎代码失败了,因为Testsuite.console从未有过初始值。

现在,代码可以对模式进行以下更改:

class Testsuite(Base):
    """Testsuite model to map testsuite in progress to SQL DB."""

    __tablename__ = 'testsuites'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    timestamp = Column(DateTime, default=datetime.datetime.utcnow)
    product_name = Column(String)
    serial_number = Column(String)
    total_tests = Column(Integer)
    completed_tests = Column(Integer, default=0)
    console = Column(String, default="Waiting for incoming log data...\n")
    report_id = Column(Integer)
    testcases = relationship('Testcase', backref='testsuite')
    result = Column(String, default='pending')

    def __init__(self, testsuite_name, product_name, serial_number, total_tests=0):
        self.name = testsuite_name
        self.product_name = product_name
        self.serial_number = serial_number
        self.total_tests = total_tests