【发布时间】:2014-07-02 15:06:31
【问题描述】:
在我的 3 个表之间创建一组关系时遇到问题。当我运行代码来创建表时,我得到一个循环依赖错误。
根据对类似帖子的回复,我尝试摆弄use_alter 和post_update,但我无法解决问题。
基本上一张地图有一组位置,一个角色有一组地图,但一个角色也位于其中一个地图位置。 此外,一个地图可以与其他地图有父/子关系。
class Character(Base):
__tablename__ = 'character'
ID = Column(Integer, primary_key=True)
name = Column(Unicode(255), nullable=False)
classID = Column(Integer, nullable=False)
created = Column(DateTime, nullable=False, default=datetime.datetime.utcnow)
profileID = Column(Integer, ForeignKey('profile.ID'), nullable=False)
locationID = Column(Integer, ForeignKey('location.ID'))
location = relationship("Location")
maps = relationship("Map", backref="owner", cascade="save-update, merge, delete, delete-orphan")
class Map(Base):
__tablename__ = 'map'
ID = Column(Integer, primary_key=True)
name = Column(Unicode(255))
maptypeID = Column(Integer, nullable=False)
created = Column(DateTime, nullable=False, default=datetime.datetime.utcnow)
parentID = Column(Integer, ForeignKey('map.ID'))
ownerID = Column(Integer, ForeignKey('character.ID'))
children = relationship("Map", backref=backref("parent", remote_side="Map.ID"))
locations = relationship("Location", backref='map', cascade="save-update, merge, delete, delete-orphan")
class Location(Base):
__tablename__ = 'location'
ID = Column(Integer, primary_key=True)
x = Column(Integer, nullable=False)
y = Column(Integer, nullable=False)
locationtypeID = Column(Integer, nullable=False)
created = Column(DateTime, nullable=False, default=datetime.datetime.utcnow)
mapID = Column(Integer, ForeignKey('map.ID'), nullable=False)
我该如何解决这个问题?
编辑(已解决):
在使用use_alter 进行了更多尝试之后,我能够通过将 Location 类中的 mapID 定义更改为:
mapID = Column(Integer, ForeignKey('map.ID'), nullable=False)
收件人:
mapID = Column(Integer, ForeignKey('map.ID', use_alter=True, name="fk_location_map"), nullable=False)
为了响应打破循环依赖的建议,我宁愿在架构中表示正确的关系和数据完整性。我宁愿担心修复 ORM 问题或更改 ORM,也不愿捏造架构以符合 ORM 的期望。
在这种特殊情况下,我想不出一种更简洁和优雅的方式来表示我需要模式来表示的所有 信息(在这个词的最基本意义上)为应用程序。
旁注:在与其他语言/框架/ORM 合作后,这种混乱通常由 ORM 自动解决。例如,在 .NET E/F 中,我相信 FK 约束通常是在所有表创建语句之后添加和激活的。
【问题讨论】:
-
如果您的问题是在架构中查找循环依赖项,这里有一个要点:gist.github.com/adewes/dea76a0cc7c56c705d74
标签: python sqlalchemy circular-dependency