donkon
donkon

Reputation: 919

SQLAlchemy failing to catch not null constraint when primary key true

Previously testing would raise an Exception when passing in None for

Column(Integer, nullable=False)

Now when I change it to be primary key true, it no longer raises an Exception

Column(Integer, nullable=False, primary_key=True)

I have tried a separate CheckConstraint() for NOT NULL but it still doesn't complain.

How do I get it to complain again when I try to commit a None/Null value for this?

Upvotes: 1

Views: 2731

Answers (1)

Lukas Graf
Lukas Graf

Reputation: 32600

SQLAlchemy defaults to autoincrement=True for primary key Integer columns - therefore in your second case, NULL is never actually inserted, and that's why the constraint is still satisfied.

Setting autoincrement=False should get you the behavior you want:

Column(Integer, nullable=False, primary_key=True, autoincrement=False)

Upvotes: 3

Related Questions