Environment:
- Django 1.10.6
- psycopg2 2.7.1
- PostgreSQL 9.6.2 installed via Homebrew on macOS Sierra
- Python 3.6.0 installed via Homebrew
Example model:
from django.db import models
from django.contrib.postgres.fields import JSONField
class Foo(models.Model):
data = JSONField()
When I try to create an object, everything works as expected:
from myapp.models import Foo
x = Foo()
x.data = {'key1': 'value1'}
x.save()
And querying works as expected:
Foo.objects.filter(data__key1='value1').count()
# 1
However, when I try to retrieve that data from the object, the value of the .data
attribute is a string:
from myapp.models import Foo
x = Foo.objects.get(id=1)
x.data
# '{"key1": "value1"}'
type(x.data)
# str
I would expect to get back a dict here. The problem gets recursively worse when trying to save back the object
x.save()
x = Foo.objects.get(id=1)
x.data
# '"{\\"key1\\": \\"value1\\"}"'
x.save()
x = Foo.objects.get(id=1)
x.data
# '"\\"{\\\\\\"key1\\\\\\": \\\\\\"value1\\\\\\"}\\""'