I am trying to build a custom JSON Field for Django projects that support MySQL. This is my models:
我正在尝试为支持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)
Please notice the custom save method for the Content model. When I try to save a new Content object, I get this error:
请注意内容模型的自定义保存方法。当我尝试保存新的Content对象时,我收到此错误:
InterfaceError at /admin/myapp/content/add/
/ admin / myapp / content / add /中的InterfaceError
Error binding parameter 2 - probably unsupported type.
错误绑定参数2 - 可能不受支持的类型。
What exactly am I doing wrong? What does the error even mean. I mean it says 'probably', as if its not even sure if there is an error. Any help?
我究竟做错了什么?这个错误甚至意味着什么。我的意思是它说'可能',好像它甚至不确定是否有错误。有帮助吗?
If you want the full traceback, you can find it here: http://pastebin.com/B15hZpbu
如果你想要完整的追溯,你可以在这里找到它:http://pastebin.com/B15hZpbu
1 个解决方案
#1
1
this code will produce an undefined variable error before you call your user method.
在调用用户方法之前,此代码将生成未定义的变量错误。
data = {
name1 : {
"image_url" : 'https://photosite.com/image1.jpg',
"views" : 0
},
name2 : {
"image_url" : 'https://photosite.com/image2.jpg',
"views" : 0
}
}
name1 and name2 are clearly not defined in your code.
name1和name2显然没有在您的代码中定义。
#1
1
this code will produce an undefined variable error before you call your user method.
在调用用户方法之前,此代码将生成未定义的变量错误。
data = {
name1 : {
"image_url" : 'https://photosite.com/image1.jpg',
"views" : 0
},
name2 : {
"image_url" : 'https://photosite.com/image2.jpg',
"views" : 0
}
}
name1 and name2 are clearly not defined in your code.
name1和name2显然没有在您的代码中定义。