1

I have a little problem:

I have this model:

class myModel(models.Model):
    myField =JSONField()

I want to update this field:

data={'rda': {'punti': 0, 'rank': 1, 'pos': 'eq'}}
a =myModel()
a.myField=data
a.save()

but I have this error:

Traceback (most recent call last): File "/home/hy0/.conda/envs/ciclods_env/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.DataError: malformed array literal: "{"rda": {"punti": 0, "rank": 1, "pos": "eq"}}"

how can I solve it?

3 Answers3

0

You must need to use PostgreSQL. I tried so far, it works for me

data = {  
    'rda':{  
        'punti':0,
        'rank':1,
        'pos':'eq'
    }
}

test = myModel()
test.myField=data
test.save()
shafik
  • 6,098
  • 5
  • 32
  • 50
0

You need an instance of myModel in order to store this. E.g. something like:

myModel.objects.create(myField={'rda': {'punti': 0, 'rank': 1, 'pos': 'eq'}})

I suspect there's some extra code in there that's not obvious, data is a dict but then you're calling save on it which normally raises an AttributeError. Also I'm guessing in your original code myModel is not an instance of myModel but rather the model itself and so you can't operate against it directly, you need an instance of it that represents the database row.

Once you have an instance of myModel, you can do:

a_model = myModel()
a_model.myField = {'rda': {'punti': 0, 'rank': 1, 'pos': 'eq'}}
a_model.save()

Just to make this clear in my answer too, you need to ensure the database field matches the one declared in your model, check you have generated migrations and applied them for all your latest changes.

Nobilis
  • 7,310
  • 1
  • 33
  • 67
  • @marcantoniosofia can you update your question to reflect the full code? As it is at the moment it seems like you operate against the model and not the instance. – Nobilis Mar 07 '19 at 11:37
0

I had this exact issue and this post is the only reference I could find to it. I'm not sure what the cause is, but I finally fixed it by removing my migration scripts for a fresh database.

If you're hitting this error, try removing the last few migration scripts, until you find the culprit. Alternatively, you can start fresh like me and it should work again.

jarthur
  • 393
  • 1
  • 2
  • 18