在Django中自定义JSONField

时间:2016-07-30 11:26:03

标签: python mysql json django django-jsonfield

我正在尝试使用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'

我到底做错了什么?我该如何解决这个问题?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

根据例外和django docs,您的get_db_prep_save方法应该再使用一个名为connection的参数,所以:

    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)

应该没事。