Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Django JSONField and TextField

Tags:

json

django

I have to save a JSON string to a Django model and am curious as to which field type I should use. I have seen a JSONField used before, but surely a TextField will do the exact same job since JSON is a string?

What type of field should I be using?

like image 709
cbuch1800 Avatar asked Jan 09 '18 16:01

cbuch1800


1 Answers

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/

like image 78
nimasmi Avatar answered Sep 22 '22 06:09

nimasmi