2

What is the best way of storing a dictionary within Django. Is there a native way of pushing the entire JSON into a field or should I try using something else...what do people recommend. I'd like to keep as standard Django as possible.

disruptive
  • 5,687
  • 15
  • 71
  • 135
  • I'm using MySQL by the way – disruptive Feb 21 '14 at 14:57
  • If you are satisfied with one of the answer, please accept it and vote it up. Also, you should do the same for your "[gold question](http://stackoverflow.com/questions/7847624/list-comprehension-for-loops-python)" – Nil Feb 21 '14 at 23:49

3 Answers3

0

If you're using PostgreSQL, you may look at django-hstore

class Something(models.Model):
    name = models.CharField(max_length=32)
    data = hstore.DictionaryField()  # can pass attributes like null, blank, ecc.

instance = Something.objects.create(name='something', data={'a': '1', 'b': '2'})
assert instance.data['a'] == '1'
erthalion
  • 3,094
  • 2
  • 21
  • 28
0

There's currently no special JSON datatype for MySQL. At one of my job, we used a normal text/blob field. Before writing it in the DB, we compact it:

>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'

And when we need to show it (if you ever need to show it?), we pretty print it:

>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
...                  indent=4, separators=(',', ': '))
{
    "4": 5,
    "6": 7
}

These snippets come from the official documentation.

Nil
  • 2,345
  • 1
  • 26
  • 33
0

There are several packages which support JSON fields on models: https://www.djangopackages.com/grids/g/json-fields/

There's one MySQL specific also: https://django-mysql.readthedocs.org/en/latest/model_fields/json_field.html

Csaba Toth
  • 10,021
  • 5
  • 75
  • 121