0

I have defined a python class "Students", like this:

class Students(DeclarativeBase):

    __tablename__ = 'students'

    id_ = Column('id', Integer, primary_key=True)

    name = Column('nombre', Unicode(50))
    date_of_birth = Column(Date)

If I do select * from students, I can see all of these columns plus a few more, namely: _created and _updated.

I need to use the values stored in the columns _created and _updated. So I try to access them like this:

#get student with id = 1
>>> s = dbs.query(Students).get(1)

# print its name
>>> print(s.name)
Richard

# try to print when it was created
>>> print (s._created)
AttributeError: 'Students' object has no attribute '_created'

Of course I get that message because the attribute _created is not defined in the model.

How can I access the value stored in the table Students even though it is not an attribute of the class Student?

1
  • 1
    And why would not you like to add these attributes to the class definition?
    – van
    Sep 23, 2014 at 18:24

1 Answer 1

2

SQLAlchemy needs the definition of each column it will access. (There are ways to auto-discover by reflecting the database, but explicit is better than implicit.) Add the column definitions to the model. I'm assuming they're DateTimes. You can use default= and onupdate= to provide new values when a row is inserted or updated.

class Student(Base):
    __tablename__ = 'student'

    id = Column('id_', Integer, primary_key=True)
    # other columns...
    created = Column('_created', DateTime, nullable=False, default=datetime.utcnow)
    updated = Column('_updated', DateTime, onupdate=datetime.utcnow)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.