darkhorse
darkhorse

Reputation: 8782

Custom JSONField in Django

I am trying to implement a custom JSON Field for my models using Django + MySQL. This is what my models.py looks like:

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)

Basically, when a content is saved, I am trying to initialize the data field. However, I get this error right now:

get_db_prep_save() got an unexpected keyword argument 'connection'

What am I exactly doing wrong? And how can I fix this? Any help would be appreciated.

Upvotes: 0

Views: 3088

Answers (1)

GwynBleidD
GwynBleidD

Reputation: 20569

According to exception and django docs, your get_db_prep_save method should take one more argument, called connection, so this:

    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)

should be okay.

Upvotes: 1

Related Questions