This thing is called referential integrity
(https://en.wikipedia.org/wiki/Referential_integrity) and is enforced on
the database level - you can't have a value in Child.parent_id which is not
in Parent.id. The ForeignKey creates a constraint in the database which
ensures the referential integrity of a column.
If you don't need it, you can define a column as a plain integer:
parent_id = Column(Integer, nullable=False)
but then SQLAlchemy won't be able to figure the joins so you'll need to
specify them manually:
parent = relationship('parent', primaryjoin='Parent.id==Child.parent_id')
On Wednesday, February 27, 2019 at 8:29:39 AM UTC+10, Daniel Leon wrote:
>
> Suppose I have a Parent and Child table with Child having
> parent_id = Column(Integer, ForeignKey('parent.id'), back_populates=
> 'children', nullable=False)
> parent = relationship('parent')
> and Parent having
> children = relationship('child', back_populates='parent')
>
> Then if I try to delete a Parent, since Child has parent_id non-nullable
> I'd get error *Cannot insert the value NULL into column parent_id*. I
> want Child to retain its parent_id after its Parent is deleted.
>
> I didn't find a cascade option that accomplishes this.
>
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
http://www.sqlalchemy.org/
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable
Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.