我正在尝试使用 Django + MySQL 为我的模型实现自定义 JSON 字段。这就是我的models.py的样子:
from __future__ import unicode_literals
from django.db import models
from django.db import models
from django.core.serializers.json import DjangoJSONEncoder
import json
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):
"""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)
# 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)
基本上,当保存内容时,我正在尝试初始化数据字段。但是,我现在收到此错误:
get_db_prep_save() got an unexpected keyword argument 'connection'
我到底在做什么错?我该如何解决这个问题?任何帮助,将不胜感激。