Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy set default value for postgres JSON column

I want to set the default value of my SQLAlchemy postgres JSON column to an empty dictionary.

from sqlalchemy.dialects.postgresql import JSON

info = Column(JSON, default='{}')
info = Column(JSON, default={})

Neither of these work.

like image 546
allenlin1992 Avatar asked Aug 15 '16 19:08

allenlin1992


Video Answer


2 Answers

Using default=lambda: {} works. Credit goes to univerio in the comments.

like image 126
allenlin1992 Avatar answered Sep 18 '22 15:09

allenlin1992


The easiest way I've found to define a JSON not null (if applies) column with a default {} value is (tested with SQLAlchemy 1.3.x):

info = db.Column(JSON, nullable=False, server_default='{}')
like image 24
Caumons Avatar answered Sep 20 '22 15:09

Caumons