3

Straightforward 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.
7
  • have you tried Foo(fooField=data) where data is a dictionary rather than a string? IE Foo(fooField=json.loads(request.data))? Commented Mar 28, 2016 at 21:50
  • @Hamms I get this error: TypeError: the JSON object must be str, not 'list' ...which begs the question, if JSON has to be 'str', then it can't possibly be jsonb[] even when saved properly (it will always be text[]) Commented Mar 28, 2016 at 21:53
  • what if you attempt something like Foo(fooField={})? Commented Mar 28, 2016 at 21:57
  • @Hamms I'm trying to save an Array of JSON objects...not a single JSON object, so that won't make sense. Commented Mar 28, 2016 at 21:58
  • 1
    @jDo you're right, if you could just post an answer mirroring mine below I'll use it as the default answer so you can get some points (I'm an SO newb, so I'll gladly give credit where credit is due) Commented Mar 28, 2016 at 22:25

1 Answer 1

5

@jDO it seems your comment is correct. There is no need to nest JSONField in ArrayField as 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!
Sign up to request clarification or add additional context in comments.

2 Comments

I wonder if there are limitations/benefits in the kind of queries we can use if we use: JSONField(default=list) vs ArrayField(JSONField())
@JoseJorgeLorenzoVila: yes there are. For instance you can filter on the length of ArrayField, like .filter(bar__len=1), but not on JSONField. For that reason, this is unfortunate that we cannot nest json on array, since it's not equivalent to a simple json field. (But anyway it's probably the sign that a better design is needed).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.