how to define a json type to a model field from django models

Can anyone tell me how to define a json data type to a particular field in models.

I have tried this

from django.db import models
import jsonfield

class Test(models.Model):
    data = jsonfield.JSONField()

but when I say python manage.py sqlall xyz its taking the data field as text

BEGIN;
CREATE TABLE "xyz_test" (
   "data" text NOT NULL
)
; 

I still tried to insert json data into that field but its giving error as :

ERROR:  value too long for type character varying(15)

someone please help. Thanks in Advance.


Solution 1:

In the background JSONField actually is a TextField, so that output from sqlall is not a problem, that's the expected behavior.

Further, I recreated your model and it worked just fine, both when entering the value as a string and as a python dictionary, no character limitation whatsoever. So my best guess it that the issue is a completely unrelated field that does have a 15 chars limit.

Solution 2:

A JSONField data type has been added to Django for certain databases to improve handling of JSON. More info is available in this post: Django 1.9 - JSONField in Models

Solution 3:

You can try this:

from django.contrib.postgres.fields import JSONField

class Test(models.Model):
    data = models.JSONField()