无法从Python模型访问PostgreSQL表中的列

时间:2014-09-23 16:41:56

标签: python postgresql sqlalchemy

我已经定义了一个python类"学生",像这样:

class Students(DeclarativeBase):

    __tablename__ = 'students'

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

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

如果我select * from students,我可以看到所有这些列以及更多内容,即:_created_updated

我需要使用_created_updated列中存储的值。所以我试着像这样访问它们:

#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'

当然我得到了那条消息,因为模型中没有定义属性_created

我如何访问表Students中存储的值,即使它不是类Student的属性?

1 个答案:

答案 0 :(得分:2)

SQLAlchemy需要它将访问的每个列的定义。 (有些方法可以通过反映数据库来自动发现,但是explicit is better than implicit。)将列定义添加到模型中。我假设他们是DateTime。在插入或更新行时,您可以使用default= and onupdate=提供新值。

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)