我正在尝试为支持 MySQL 的 Django 项目构建自定义 JSON 字段。这是我的模型:
from __future__ import unicode_literals
from django.db import models
from django.db import models
from django.core.serializers.json import DjangoJSONEncoder
import json
name1 = 'name1'
name2 = 'name2'
class JSONField(models.TextField):
"""JSONField is a generic textfield that neatly serializes/unserializes
JSON objects seamlessly"""
# Used so to_python() is called
__metaclass__ = models.SubfieldBase
def to_python(self, value):
"""Convert our string value to JSON after we load it from the DB"""
if value == "":
return None
try:
if isinstance(value, basestring):
return json.loads(value)
except ValueError:
pass
return value
def get_db_prep_save(self, value, connection):
"""Convert our JSON object to a string before we save"""
if value == "":
return None
if isinstance(value, dict):
value = json.dumps(value, cls=DjangoJSONEncoder)
return super(JSONField, self).get_db_prep_save(value, connection)
# Articles / Content
class Content(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
data = JSONField(blank=True, null=True)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.data = {
name1 : {
"image_url" : 'https://photosite.com/image1.jpg',
"views" : 0
},
name2 : {
"image_url" : 'https://photosite.com/image2.jpg',
"views" : 0
}
}
super(Content, self).save(*args, **kwargs)
请注意 Content 模型的自定义保存方法。当我尝试保存新的 Content 对象时,出现此错误:
/admin/myapp/content/add/ 处的接口错误
错误绑定参数 2 - 可能是不受支持的类型。
我到底做错了什么?错误甚至意味着什么。我的意思是它说“可能”,好像它甚至不确定是否有错误。有什么帮助吗?
如果你想要完整的追溯,你可以在这里找到它:http: //pastebin.com/B15hZpbu