postgresql 如何从 django 模型将 json 类型定义为模型字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25884534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to define a json type to a model field from django models
提问by G-Coder
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.
有人请帮忙。提前致谢。
采纳答案by yuvi
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. So my best guess it that the issue is a completely unrelated field that doeshave a 15 chars limit.
此外,我重新创建了您的模型并且它工作得很好,无论是作为字符串还是作为 python 字典输入值时,都没有任何字符限制。所以我最好猜测这个问题是一个完全不相关的字段,它有 15 个字符的限制。
回答by Ben
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
JSONField 数据类型已添加到某些数据库的 Django 中,以改进对 JSON 的处理。这篇文章提供了更多信息:Django 1.9 - 模型中的 JSONField