I've been playing around with SQLAlchemy at the interactive Python
prompt, and I've discovered an interesting quirk. I can't tell if it's
a bug or not; if it's not a bug, then perhaps someone can explain why
it acts this way.
I created a simple table structure:
from sqlalchemy import *
engine = create_engine('sqlite://filename=foo.db')
class Person(object):
pass
person = Table('person', engine,
Column('id', Integer, Sequence('person_id_seq'), primary_key=True),
Column('lname', String),
Column('fname', String),
Column('age', Integer),
)
person.create()
assign_mapper(Person, person)
And then went to the Python prompt and pasted the above in. Then I
created a couple of Person objects:
>>> john = Person(fname='John', lname='Doe', age=42)
>>> mary = Person(fname='Mary', lname='Smith') # Age not given
>>> objectstore.commit()
>>> john.fname
'John'
>>> john.age
42
>>> mary.fname
'Mary'
>>> mary.age
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/home/rmunn/projects/python/sqlalchemy/lib/sqlalchemy/attributes.py",
line 51, in get_prop
return self.attribute_registry().get_attribute(obj, key)
File "/home/rmunn/projects/python/sqlalchemy/lib/sqlalchemy/attributes.py",
line 275, in get_attribute
raise AttributeError(key)
AttributeError: age
I'd been expecting to get "None" for Mary's age, since it's a NULL in
the database. If I quit the Python interpreter and come back to it,
then things work as I expect:
>>> john = Person.get(1)
>>> mary = Person.get(2)
>>> john.fname
u'John'
>>> mary.fname
u'Mary'
>>> john.age
42
>>> mary.age
>>> mary.age is None
True
But if I create a Person object without specifying its age, and then
try to get the "age" attribute within the same Python session, it
fails with an AttributeError exception. I tried working around this by
doing an objectstore.commit() and fetching the object back with
Person.get(), but that doesn't work:
>>> susan = Person(fname='Susan', lname='Smith') # No age given
>>> objectstore.commit()
>>> susan.fname
'Susan'
>>> susan.id
3
>>> new_obj = Person.get(3)
>>> new_obj is susan
True
>>> # Probably won't work then, but let's try it
...
>>> new_obj.age
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/home/rmunn/projects/python/sqlalchemy/lib/sqlalchemy/attributes.py",
line 51, in get_prop
return self.attribute_registry().get_attribute(obj, key)
File "/home/rmunn/projects/python/sqlalchemy/lib/sqlalchemy/attributes.py",
line 275, in get_attribute
raise AttributeError(key)
AttributeError: age
Is this expected behavior? How should I go about fetching the age
value for a Person object I've just created, if I didn't specify one
in the first place? I've been reading through the documentation; if
there's anything that talks about this case, I haven't found it yet.
Any help would be appreciated.
--
Robin Munn
[EMAIL PROTECTED]
GPG key 0xD6497014