当嵌套为ArrayField()的子节点时,JSONField()无法正确保存

时间:2016-03-28 21:47:08

标签: python django postgresql

直截了当的问题:使用Django 1.9+和PostgreSQL 9.4.6将字段设置为ArrayField(JSONField(...),...)在保存时不起作用

# models.py
class Foo(models.Model):
    bar = ArrayField(JSONField(blank=True, null=True), default=list([]))

# app.py
...
data = request.data #ie. [{...}, {...}] 
# variations that were tested:
# JSON.stringify([{...}, {...}, ...])
# JSON.stringify([JSON.stringify({...}), JSON.stringify({...}), ...]
# any mix of non-JSON.stringified and stringified objects being sent via AJAX

Foo(bar=data)

# error message:
django.db.utils.ProgrammingError: column "bar" is of type \
jsonb[] but expression is of type text[]
LINE 1: INSERT INTO "app_foo" ("bar") VALUES (ARRAY['{"name": ...
                                                ^
HINT:  You will need to rewrite or cast the expression.

1 个答案:

答案 0 :(得分:4)

@jDO看来你的评论是正确的。由于JSONField支持列表,因此无需在ArrayField中嵌套JSONField。这是更新的代码:

# models.py
class Foo(models.Model):
    bar = JSONField(default=list([]))

# app.py
...
data = request.data #ie. [{...}, {...}] 
Foo(bar=data)

# works!