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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With