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.
Many a time, on developer website, we need to add developer data and JSON fields are useful in such cases. First create a Django project and an app. Please do all the basic things, like adding app in INSTALLED_APPS and setting up urls, making a basic model and render its form in an HTML file.
django-json-field contains a flexible JSONField and associated form field. The model field is not only capable of serializing common JSON data types (int, float, decimal, string, time, date, datetime, etc.) but also lazily deserializing them so they can be accessed and modified as normal Python objects within Django.
When you make a model class in Django, consider that class the data-table, each individual instance of that class the table rows, and the attributes(e.g: title) of each table the columns. In the definition of the class Book, title seems to be a class attribute.
The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this. Note: how objects are just plainly numbered. to this.
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.
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
You can try this:
from django.contrib.postgres.fields import JSONField
class Test(models.Model):
data = models.JSONField()
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