【问题标题】:SQLAlchemy AssertionError: Dependency rule tried to blank-out primary key columnSQLAlchemy AssertionError:依赖规则试图清空主键列
【发布时间】:2020-05-26 07:57:09
【问题描述】:

因为下面一行:contact_person.selections_to_persons[selection_id].post_address = address

我在下一次提交时收到以下错误:

AssertionError: 依赖规则试图清除实例“”上的主键列“selections_to_persons.t_person_to_department_id”

涉及的模型的重要部分是:

class SelectionToPerson(OrmModelBase, TableModelBase):
    __tablename__ = 'selections_to_persons'
    __table_args__ = (
        ForeignKeyConstraint(
            ["address_tablename",
             "address_id",
             "t_person_to_department_id"],

            ["address_collection.tablename",
             "address_collection.id",
             "address_collection.t_person_to_department_id"],
            name="fk_post_address_selection_to_person", use_alter=True
        ),
    )

    selection_id = Column(Integer,
                          ForeignKey('selections.selection_id',
                                     onupdate=NO_ACTION,
                                     ondelete=CASCADE),
                          primary_key=True, nullable=False)
    t_person_to_department_id = Column(
        Integer,
        ForeignKey('t_persons_to_departments.t_person_to_department_id',
                   onupdate=NO_ACTION,
                   ondelete=CASCADE),
        primary_key=True,
        nullable=False)
    address_tablename = Column(String, nullable=False)
    address_id = Column(Integer, nullable=False)

    post_address = relationship(AddressCollection)

class AddressCollection(OrmModelBase, ViewModelBase):
    __tablename__ = 'address_collection'

    tablename = Column(String, primary_key=True)
    id = Column(Integer, primary_key=True)

    t_person_to_department_id = Column(
        Integer,
        ForeignKey('t_persons_to_departments.t_person_to_department_id'),
        primary_key=True)

有谁知道为什么会出现这个错误?

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    发生此错误的一种情况是尝试将 null 分配给作为主键的字段。

    您有几个由外键指定的主键。 我不确定,但表达式contact_person.selections_to_persons[selection_id].post_address = address 可能创建了一个具有空引用的对象。也就是说,在赋值之后,一些对象仍然是一个空引用。

    我将留下几个链接来描述如何在不同情况下使用级联。这可能会对遇到此错误的人有所帮助。

    这是级联的工作方式: https://docs.sqlalchemy.org/en/13/orm/cascades.html#unitofwork-cascades

    以下是使用删除示例配置级联的方法:https://docs.sqlalchemy.org/en/13/orm/tutorial.html#configuring-delete-delete-orphan-cascade

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多