24

I'm trying to set up a models file in Django 1.9 using the new JSONField. I have found examples using postgres but none with MySql. In the examples with postgres they do a

from django.contrib.postgres.fields import JSONField

How do I go about importing it for MySql? Thanks

Ravash Jalil
  • 820
  • 1
  • 9
  • 19

7 Answers7

48

UPDATE: Django 3.1 now supports JSONField natively for multiple databases: https://docs.djangoproject.com/en/dev/releases/3.1/#jsonfield-for-all-supported-database-backends


As stated in other answers, Django's native JSONField (as of 1.9 and 1.10) is for PostgreSQL.

Luckily, MySQL 5.7.8+ comes with a native JSON datatype. You can add it your Django project with the django-mysql package and Django 1.8+

pip install django-mysql

from django.db import models
from django_mysql.models import JSONField

class MyModel(models.Model):
    my_json_field = JSONField()

Read more about the django_mysql JSONField here.

aboutaaron
  • 4,869
  • 3
  • 36
  • 30
  • 1
    This should be the answer – kbuilds Oct 30 '17 at 21:12
  • And what should a serializer for such a model look like?! I'm using `django-mysql` but cannot figure out how to construct a serializer. Would you please, give me a hint or something. I'd very much appreciate it. – Albert Oct 29 '18 at 15:50
  • @Albert you shouldn't need a serializer. Django-MySQL will take anything `json.dumps` takes and will store it as JSON. I believe you'd only need a serializer if you wanted to take row in the database and return it as JSON (for example, in an API.) In that case, you should use something like django-rest-framework. See the docs for the JSONField here: https://django-mysql.readthedocs.io/en/latest/model_fields/json_field.html – aboutaaron Oct 29 '18 at 17:43
20

Django JSONField is Postgres only.

https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#django.contrib.postgres.fields.JSONField

UPDATE:

There is support for MYSQL via 3rd party library django-mysql

Greg Sadetsky
  • 4,863
  • 1
  • 38
  • 48
richard_
  • 417
  • 2
  • 11
6
# Install jsonfield package
pip install jsonfield

# Define my model
from django.db import models
import jsonfield

class MyModel(models.Model):
    the_json = jsonfield.JSONField()

More detail:https://pypi.python.org/pypi/django-jsonfield

Solaman Raji
  • 170
  • 9
Son Lam
  • 1,229
  • 11
  • 16
2

I know this question is about Django 1.9, but JSONField can now be used with all supported database backends with the release of Django 3.1.

Hemang Kumar
  • 91
  • 2
  • 7
2

Try to save data of this model in postgres db on my local machine:

models.py:

from django.db import models
from django import forms
 
from inputData.models import Input
 
from django.contrib.postgres.fields import JSONField
 
class Results(models.Model):
 
    generator = models.OneToOneField(Input, on_delete = models.CASCADE, primary_key = True)
 
    pvalues = JSONField()

views.py

def result(req, res_id):
    try:
        inp = Input.objects.get(pk = res_id)
        path = os.path.join(BASE_DIR, 'uploads\\' + str(res_id) + '\\t.txt')
        p_values = parse_res.main(path) 
        res = Results(generator = inp, pvalues = p_values)
        res.save(using = 'results')
    except Results.DoesNotExist:
        raise Http404
    return render(req, 'result.html', {'res': res})

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'results': {
        'ENGINE':'django.db.backends.postgresql',
        'NAME': 'results',
        'PASSWORD': 'password',
        'USER': 'user',
        'HOST': '127.0.0.1',
        'PORT': '8000'

    }
    
}

Model Results (see models.py) uses JSONField, which have about 200 bytes of data But at the line res.save(... of code views.py browser does response too long.

Whatäs wrong with JSON? What problems can be on server besides cache?

1

For today I'd recommend using jsonfield2 or waiting for native JSON support for all database backends in Django 3.

maciek
  • 3,198
  • 2
  • 26
  • 33
0

Now in MySQL you can use default models.JSONFile, for more details read here https://docs.djangoproject.com/en/4.2/topics/db/queries/#querying-jsonfield

from django.db import models

class modelName(models.Model):
     name = models.CharField(max_length=200)
     data = models.JSONField(default=dict, null=True)

     def __str__(self):
          return self.name
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69