[英]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.谁能告诉我如何为模型中的特定字段定义 json 数据类型。
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但是当我说python manage.py sqlall xyz
时,它将数据字段作为文本
BEGIN;
CREATE TABLE "xyz_test" (
"data" text NOT NULL
)
;
I still tried to insert json data into that field but its giving error as :我仍然尝试将 json 数据插入该字段,但它给出的错误为:
ERROR: value too long for type character varying(15)
someone please help.有人请帮忙。 Thanks in Advance.提前致谢。
In the background JSONField actually is a TextField , so that output from sqlall is not a problem, that's the expected behavior.在后台JSONField 实际上是一个 TextField ,因此 sqlall 的输出不是问题,这是预期的行为。
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.此外,我重新创建了您的模型并且它工作得很好,无论是作为字符串输入值还是作为 Python 字典输入时,都没有任何字符限制。 So my best guess it that the issue is a completely unrelated field that does have a 15 chars limit.所以我最好猜测这个问题是一个完全不相关的字段,它有 15 个字符的限制。
A JSONField data type has been added to Django for certain databases to improve handling of JSON.已将 JSONField 数据类型添加到某些数据库的 Django,以改进对 JSON 的处理。 More info is available in this post: Django 1.9 - JSONField in Models这篇文章提供了更多信息: Django 1.9 - 模型中的 JSONField
You can try this:你可以试试这个:
from django.contrib.postgres.fields import JSONField
class Test(models.Model):
data = models.JSONField()
First install django-jsonfield
pypi package:首先安装django-jsonfield
pypi 包:
pip install django-jsonfield
Then simply use it:然后简单地使用它:
class MyModel(models.Model):
custom_field = JSONField(
default=dict
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.