首页 > 解决方案 > 尝试将对象属性映射到不同名称的数据库列

问题描述

我是一个新用户,正在 Python 中使用 SQLAlchemy 和 mysql。我有一个映射到客户表的客户对象。我决定以不同于数据库中列名的方式命名对象属性。SQLAlchemy 1.3.11 的文档表明这应该是允许的。

我的课看起来像这样

class Customer(declarative_base(), PersistentBase.PersistentBase):
    __tablename__ = 'customers'

    id = Column(BigInteger, primary_key=True, autoincrement=True)
    first_name = Column('firstName', String(35), nullable=False)
    last_name = Column('lastName', String(35), nullable=False)

当我尝试执行诸如检索之类的操作时,出现以下错误:

AttributeError: 'Customer' object has no attribute 'firstName'

难道我不能这样做。我在类中的属性是被映射到列 firstName 的 first_name。

任何帮助将不胜感激。

标签: pythonsqlalchemy

解决方案


I am sorry. I had a typo in another part of my code which printed a retrieved object which was causing this error. My apologies.


推荐阅读