JSONField () is not saved properly when it is nested in a child of ArrayField ()

A simple question: setting a field as ArrayField (JSONField (...), ...) using Django 1.9+ and PostgreSQL 9.4.6 does not work when saving

# 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.
+4
source share
1 answer

@jDO your comment seems to be correct. There is no need to embed a JSONField in an ArrayField, since JSONField supports lists. Here is the updated code:

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

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

# works!
+4
source

All Articles