[Solved]-Difference between Django JSONField and TextField


This is true to an extent, but with PostgreSQL (now all database backends, see below) at least there is a specific database JSON field type. This means you can query a model based on the contents of that field. From the Django documentation https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#querying-jsonfield:

>>> Dog.objects.create(name='Rufus', data={
...     'breed': 'labrador',
...     'owner': {
...         'name': 'Bob',
...         'other_pets': [{
...             'name': 'Fishy',
...         }],
...     },
... })
>>> Dog.objects.create(name='Meg', data={'breed': 'collie'})

>>> Dog.objects.filter(data__breed='collie')
<QuerySet [<Dog: Meg>]>

Additionally, when you do dog.data, the field value is automatically converted to its native Python format, in this case a dictionary. With a TextField you’d have to do data = json.reads(dog.data) as an explicit step. (I believe this happens in the field type’s from_db_value() method.)

Update 4 August 2020: from Django 3.1 onwards, JSONField can be used in all supported database backends https://www.djangoproject.com/weblog/2020/aug/04/django-31-released/

Leave a comment