sqlalchemy ORM无法加载数据[属性的延迟加载程序无法正确填充]

时间:2014-01-03 17:32:18

标签: python sql-server sqlalchemy

我在专有的MSSQL数据库中有一个表。

from sqlalchemy import Column, Integer, Sequence
from sqlalchemy.dialects.mssql import TINYINT, NCHAR
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'my_table'
    ID = Column(Integer, Sequence('my_table_ID_seq'), primary_key=True)
    MyDescription = Column(NCHAR(20), nullable=False)
    other_data = Column(TINYINT, nullable=False)
    another_ID = Column(Integer, nullable=False)

我可以创建一个引擎并运行一个没有问题的查询

from sqlalchemy import create_engine

connection_string = "mssql+pymssql://..."
engine = create_engine(connection_string, echo=False)
result = engine.execute("SELECT MyDescription FROM my_table")
for row in result:
    print row[0]

这会产生预期的输出,但如果我尝试通过会话进行查询,则无法访问MyDescription字段

from sqlalchemy.orm import sessionmaker
session = sessionmaker(bind=engine)()

session.query(MyTable).first().MyDescription

然后我得到这个令人讨厌的消息(在这种情况下来自ipython)关于互联网在这个问题上所说的很少。

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-4-9a0ce6f4e942> in <module>()
----> 1 session.query(MyTable).first().MyDescription

c:\Python27\lib\site-packages\sqlalchemy-0.8.0b2-py2.7-win32.egg\sqlalchemy\orm\attributes.pyc in __get__(self, instance, owner)
    249             return dict_[self.key]
    250         else:
--> 251             return self.impl.get(instance_state(instance), dict_)
    252 
    253 

c:\Python27\lib\site-packages\sqlalchemy-0.8.0b2-py2.7-win32.egg\sqlalchemy\orm\attributes.pyc in get(self, state, dict_, passive)
    557                                 "Deferred loader for attribute "
    558                                 "%r failed to populate "
--> 559                                 "correctly" % key)
    560                 elif value is not ATTR_EMPTY:
    561                     return self.set_committed_value(state, dict_, value)

KeyError: "Deferred loader for attribute 'MyDescription' failed to populate correctly"

source(见第584行)非常模糊,但确实表明缺乏测试覆盖率。这可以发生什么?

1 个答案:

答案 0 :(得分:1)

我刚刚解决了。我正在使用pymssql驱动程序。将此更改为pyodbc将其排序。

connection_string = "mssql+pyodbc://..."

知道为什么吗?