简体   繁体   English

如何在 sqlAlchemy (postgreSQL) 中为 JSONB 列设置更复杂的默认值

[英]How to set a more complex default value for a JSONB column in sqlAlchemy (postgreSQL)

I'm adding a new column to a table of type JSONB and I can not find the formatting necissary to set the default value to anything other than a empty object.我正在向 JSONB 类型的表添加一个新列,但我找不到将默认值设置为空 object 以外的任何值的格式。

How would I accomplish this?我将如何做到这一点?

Currently my code looks akin to: new_column = db.Column(JSONB, server_default=db.text("'{}'"), nullable=False)目前我的代码看起来类似于: new_column = db.Column(JSONB, server_default=db.text("'{}'"), nullable=False)

I've tried a few ways I thought might be the intuitive way of handeling it.我已经尝试了一些我认为可能是处理它的直观方式的方法。 But so far they just cause an error when being run.但到目前为止,它们只是在运行时导致错误。

Example 1: new_column = db.Column(JSONB, server_default=db.text("'{'enabled': True}'"), nullable=False)示例 1: new_column = db.Column(JSONB, server_default=db.text("'{'enabled': True}'"), nullable=False)

Example 2: new_column = db.Column(JSONB, server_default=db.text("'{enabled: True}'"), nullable=False)示例 2: new_column = db.Column(JSONB, server_default=db.text("'{enabled: True}'"), nullable=False)

I wonder if the solution isn't to pass a thing that Python knows will convert to JSON rather than something that's already JSON-encoded:我想知道解决方案是否不是通过 Python 知道将转换为 JSON 而不是已经 JSON 编码的东西:

new_column = db.Column(JSONB, server_default={'enabled': True}, nullable=False)

And maybe you need to set the regular default too:也许您还需要设置常规默认值:

default = {'enabled': True}
new_column = db.Column(JSONB, default=default, server_default=default, nullable=False)

If these suggestions don't help you'll probably need to post your error messages so that people can better understand what's going wrong.如果这些建议没有帮助,您可能需要发布错误消息,以便人们更好地了解问题所在。 "It throws an error" doesn't help understand where things go wrong, which is crucial to figure out how to get them to go right. “它引发错误”无助于理解 go 错误的地方,这对于弄清楚如何让它们正确到达 go 至关重要。

Ilja Everilä's answer was the answer. Ilja Everilä 的回答就是答案。 In python I had to format the line of code in the style of:在 python 中,我必须将代码行格式化为:

server_default=db.text("'{\"enabled\": \"true\"}'")

Tripple quotes work too if you don't want escape characters, but this looks nicer to my eyes如果您不想要转义字符,三重引号也可以使用,但这在我看来更好看

Still unsure how I would pass the booleen value of true instead of a string.仍然不确定我将如何传递 true 的布尔值而不是字符串。 But that is another question for another time.但这是另一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM