Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 913
G-Coder Avatar asked Sep 17 '14 07:09

G-Coder


People also ask

How use JSON field in Django model?

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.

What is JSON field in Django model?

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.

How will you define the model classes in 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.

What is __ Str__ in Django model?

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.


3 Answers

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.

like image 110
yuvi Avatar answered Oct 19 '22 08:10

yuvi


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

like image 32
Ben Avatar answered Oct 19 '22 09:10

Ben


You can try this:

from django.contrib.postgres.fields import JSONField

class Test(models.Model):
    data = models.JSONField()
like image 3
poonam shinde Avatar answered Oct 19 '22 08:10

poonam shinde