设置JSON列的默认值 [英] Setting default value for a json column

查看:1160
本文介绍了设置JSON列的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究使用Postgres通过activerecords将json设置为列的功能 json处理功能我想知道如何在创建表时给它一个默认值,例如 {name:``,other_name:''} 等等...

I am looking at using Postgres's feature of setting json into a column via activerecords json handling features I am wondering how I would give it a default value upon table creation of something like {name: '', other_name: ''} and so on ...

我还希望了解如何为列创建默认的json值,例如上面的示例,然后再填充值,但是在

I am also looking to understand how if I create a default json value for a column, like the example above and then later on I fill in the values, but then at a some other time reset it back to "default" how that would look.

推荐答案

就像其他默认设置一样,一旦修复,就可以将其重置为默认外观。 JSON语法:

It's just like any other default, once you fix up the json syntax:

CREATE TABLE mytable (
    someothercol integer,
    somecol json DEFAULT '{"name": "", "other_name": ""}'
);

如果设置为 DEFAULT ,只是这样:

If you set to DEFAULT, it does just that:

regress=> INSERT INTO mytable(someothercol, somecol) VALUES (42, '{"nondefault": 1}');
INSERT 0 1
regress=> SELECT * FROM mytable;
 someothercol |      somecol      
--------------+-------------------
           42 | {"nondefault": 1}
(1 row)

regress=> UPDATE mytable SET somecol = DEFAULT WHERE someothercol = 42;
UPDATE 1
regress=> SELECT * FROM mytable;
 someothercol |            somecol             
--------------+--------------------------------
           42 | {"name": "", "other_name": ""}
(1 row)

这篇关于设置JSON列的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆