Let's say I have two models
class EntityModel(DB.Model): id = DB.Column(DB.Unicode(37), primary_key=True) class DocumentModel(DB.Model): id = DB.Column(DB.Unicode(37), primary_key=True) entity_id = DB.Column(DB.Unicode(37), DB.ForeignKey('entity.id', ondelete='cascade'), nullable=True) entity = DB.relationship('EntityModel')
I can create new Document with entity_id NULL. But once I set valid entity_id to that document I can no more null it back. I get error:
Cannot add or update a child row: a foreign key constraint fails
How can I set null to entity_id in some document, if it has valid entity_id?
A foreign key containing null values cannot match the values of a parent key, since a parent key by definition can have no null values. However, a null foreign key value is always valid, regardless of the value of any of its non-null parts.
From SQLAlchemy docs: nullable – If set to the default of True, indicates the column will be rendered as allowing NULL, else it's rendered as NOT NULL. This parameter is only used when issuing CREATE TABLE statements.
A foreign key in SQL is a table-level construct that constrains one or more columns in that table to only allow values that are present in a different set of columns, typically but not always located on a different table.
¶ The SQLAlchemy ORM, in order to map to a particular table, needs there to be at least one column denoted as a primary key column; multiple-column, i.e. composite, primary keys are of course entirely feasible as well.
your ORM definition looks fine, DocumentModel.entity_id is nullable indeed. What I would do in this case is check the actual table definition in MySQL and make sure it corresponds with your ORM definition, e.g.
-- make sure DocumentModel.entity_id is nullable : SHOW CREATE TABLE DocumentModel\G UPDATE DocumentModel.entity_id SET entity_id = NULL WHERE entity_id = XXX;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With