【发布时间】:2015-02-19 13:53:20
【问题描述】:
我正在学习 SQLAlchemy,我今天阅读了很多关于关系的文章,其中包括一些关于 SO 的帖子。然而,我发现没有一个例子能完全回答这个问题,尽管我认为这将是处理关系时最先回答的问题之一。
我有网页表单数据,其中很多是重复的 - 例如访问者浏览器用户代理字符串、提供表单的域和提供表单的域。我想保留这些数据,但显然将诸如代理之类的东西存储在他们自己的表中,然后在表单数据表中保留一个 ID 更有意义。所以我有一个像这样的代理类:
class Agent(Base):
__tablename__ = 'agents'
__table_args__ = {'mysql_engine': 'InnoDB'}
ID = Column(Integer, autoincrement = True, primary_key = True)
UserAgent = Column(VARCHAR(256), nullable = False, unique = True)
#UniqueConstraint('UserAgent')
def __repr__(self):
return "<Agent(UserAgent='%s')>" % (self.UserAgent)
然后我有一个表单数据类:
class Lead(Base):
__tablename__ = 'leads'
__table_args__ = {'mysql_engine': 'InnoDB'}
ID = Column(String(32), primary_key = True)
AgentID = Column(Integer, ForeignKey('agents.ID'), nullable = False)
.... other non relational fields ....
IsPartial = Column(Boolean, nullable = False)
Agent = relationship('Agent', backref = backref('leads', uselist = True))
def __repr__(self):
return "<Lead(ID='%s')>" % (self.ID)
此时,SQLAlchemy 创建了我要求它创建的所有表,并且我可以创建一个测试 Lead 实例:
testLead = Lead(ID='....', ...)
然后创建一个测试代理实例:
testAgent = Agent(UserAgent='...', leads=testLead)
testLead 实例化得很好。但是,代理实例化失败:
TypeError: Incompatible collection type: Lead is not list-like
使用 testLead.Agent = [...] 结果:
AttributeError: 'list' object has no attribute '_sa_instance_state'
理想情况下,我希望能够使用 Agent 字符串实例化 Lead 对象。然后,当我使用 session.add 和 session.commit 时,如果缺少,则让 ORM 将代理字符串添加到代理表中。同样,当我实例化 Lead 类时,我希望能够这样做:
lead = Lead(ID='...')
如果我使用:
lead.Agent
代理字符串应该会显示出来。如果我正确阅读了文档,则需要添加一些延迟加载设置。
有没有办法做到这一点?如果没有,如何解决上述错误?
谢谢
【问题讨论】:
标签: python mysql sqlalchemy