Simon Rechermann
Simon Rechermann

Reputation: 501

SQLAlchemy AssertionError: Dependency rule tried to blank-out primary key column

because of the following line: contact_person.selections_to_persons[selection_id].post_address = address

i get the following error at the next commit:

AssertionError: Dependency rule tried to blank-out primary key column 'selections_to_persons.t_person_to_department_id' on instance ''

The important parts of the involved models are:

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)

Does anyone know why this error occurs?

Upvotes: 1

Views: 3334

Answers (1)

foske
foske

Reputation: 106

One of the cases when this error occurs is an attempt to assign null to a field that is a primary key.

You have several primary keys that are specified by foreign keys. I don't know for sure, but it is possible that the expression contact_person.selections_to_persons[selection_id].post_address = address created an object with null reference. That is, after assignment, some object remains with a null reference.

I am leaving a few links that describe how to use cascades in different cases. This might help those who get this error.

This is how cascades work: https://docs.sqlalchemy.org/en/13/orm/cascades.html#unitofwork-cascades

Here's how you can configure cascades using the example of deleting: https://docs.sqlalchemy.org/en/13/orm/tutorial.html#configuring-delete-delete-orphan-cascade

Upvotes: 4

Related Questions