Python开发 常见异常和解决办法
1.sqlalchemy创建外键关系报错property of that name exists on mapper
SQLAlchemy是Python编程语言下的一款开源软件,提供了SQL工具包及对象关系映射(ORM)工具,使得在Python中操作MySQL更加简单。在给两个表创建外键关系时可能会报错:
sqlalchemy.exc.ArgumentError: Error creating backref 'xxx' on relationship 'xxx.xxx': property of that name exists on mapper 'mapped class xxx->xxx'
两个数据模型如下:
class Website(Base):
__tablename__ = 'website'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(10), nullable=False)
link = Column(String(40), nullable=False)
orders = relationship('Order', backref='website')
class Order(Base):
__tablename__ = 'order'
id = Column(String(50), primary_key=True)
desc = Column(Text, nullable=False)
link = Column(String(80), nullable=False)
contact = Column(String(30))
category = Column(String(15))
is_valid = Column(Boolean, nullable=False)
add_time = Column(DateTime, default=datetime.now)
website = Column(Integer, ForeignKey('website.id'), nullable=False)