Graeme Stuart
Graeme Stuart

Reputation: 6053

sqlalchemy ORM fails to load data [Deferred loader for attribute failed to populate correctly]

I have a table in a proprietary MSSQL database.

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)

I can create an engine and run a query without problems

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]

this results in the expected output but if I try to query via a session, I cannot access the MyDescription field

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

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

Then I get this nasty message (from ipython in this case) about which the internet says very little on the matter.

---------------------------------------------------------------------------
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"

The source (see line 584) is pretty obscure but does indicate a lack of test coverage. What can be going on here?

Upvotes: 4

Views: 1690

Answers (1)

Graeme Stuart
Graeme Stuart

Reputation: 6053

I just worked it out. I was using the pymssql driver. Changing this to pyodbc sorted it out.

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

Any idea why?

Upvotes: 1

Related Questions