gpt4 book ai didi

python - sqlalchemy.exc.CircularDependencyError : Circular dependency detected 错误

转载 作者:太空狗 更新时间:2023-10-29 18:24:30 24 4
gpt4 key购买 nike

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

同时,一个类别可以按属性值排序(这存储在 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.

最佳答案

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

所以我在 Category 类中所做的是这样更改的:

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
)

关于python - sqlalchemy.exc.CircularDependencyError : Circular dependency detected 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18284464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com