Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy allow null as ForeignKey

Tags:

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?

like image 926
ma2s Avatar asked Apr 21 '15 18:04

ma2s


People also ask

Can a foreign key be null?

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.

What is nullable SQLAlchemy?

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.

What is foreign key in SQLAlchemy?

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.

Does SQLAlchemy require primary key?

¶ 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.


1 Answers

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; 
like image 105
MOCKBA Avatar answered Oct 25 '22 23:10

MOCKBA