sqlalchemy.exc.CircularDependencyError:检测到循环依赖关系

时间:2013-08-17 02:16:54

标签: python sqlalchemy circular-dependency

业务逻辑 - 一个类别可能有多个(1:M)属性,如类别“内存”可能具有属性速度,大小,类型等。

同时一个Category可以按属性值排序(它存储在Category.sortByAttribute中 - 这是LookupCategoryAttributes表的外键。

尝试通过SQLAlchemy构建它,但检测到循环依赖。有什么问题?

class Attribute(Base):

    __tablename__ = "LookupCategoryAttributes"

    types = ["date", "float", "integer", "select", "string", "text"]

    # Properties
    ID                       = Column(BigInteger,    primary_key=True)
    categoryID               = Column(BigInteger,    ForeignKey('LookupCategories.ID'), nullable=False )
    attribute                = Column(VARCHAR(255),  nullable=False)
    listValues               = Column(VARCHAR(4000))
    typeID                   = Column(VARCHAR(40),   nullable=False)
    isRequired               = Column(SmallInteger,  nullable=False, default=0)
    displayInMenu            = Column(SmallInteger,  nullable=False, default=0)
    displayInFilter          = Column(SmallInteger,  nullable=False, default=0)


class Category(Base):

    __tablename__ = "LookupCategories"

    # Properties
    ID                       = Column(BigInteger,    primary_key=True)
    category                 = Column(VARCHAR(255),  nullable=False)
    description              = Column(VARCHAR(1000), nullable=False)
    parentCategoryID         = Column(BigInteger,    ForeignKey('LookupCategories.ID'))
    leftPos                  = Column(Integer)
    rightPos                 = Column(Integer)
    sortByAttribute          = Column(BigInteger,    ForeignKey('LookupCategoryAttributes.ID'))
    sortOrder                = Column(SmallInteger,  default=1)


    # Relationships
    ParentCategory    = relationship("Category",  uselist=False, remote_side=[ID], backref='SubCategories')
    SortByAttribute   = relationship("Attribute", uselist=False, foreign_keys=[sortByAttribute], primaryjoin="Attribute.ID==Category.sortByAttribute")
    Attributes        = relationship("Attribute", backref="Category", primaryjoin="Attribute.categoryID==Category.ID")

然后代码如下:

category = Category(record['Name'], extID=extID)
attr1 = Attribute(v)
attr2 = Attribute(v)

category.Attributes.append(attr1)
category.Attributes.append(attr2)
category.SortByAttribute = attr1

当我执行提交时,我得到:

sqlalchemy.exc.CircularDependencyError: Circular dependency detected.

1 个答案:

答案 0 :(得分:14)

好的找到答案 - 在关系中使用post_update http://docs.sqlalchemy.org/en/latest/orm/relationship_persistence.html#post-update

所以我所做的是在类别类中改变了这个:

SortByAttribute = relationship(
    "Attribute",
    uselist=False,
    foreign_keys=[sortByAttribute],
    primaryjoin="Attribute.ID==Category.sortByAttribute"
)

到此:

SortByAttribute = relationship(
    "Attribute",
    uselist=False,
    foreign_keys=[sortByAttribute],
    primaryjoin="Attribute.ID==Category.sortByAttribute",
    post_update=True
)