0

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.

darkhorse
  • 8,192
  • 21
  • 72
  • 148

1 Answers1

1

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.

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
GwynBleidD
  • 20,081
  • 5
  • 46
  • 77
  • Now I get this error : get_db_prep_save() takes exactly 3 arguments (2 given) referencing the line return super(JSONField, self).get_db_prep_save(value). However, changing this to return super(JSONField, self).get_db_prep_save(value, connection) returns a new error : INTERFACE ERROR - Error binding parameter 2 - probably unsupported type. – darkhorse Jul 30 '16 at 11:32
  • 1
    You must pass `connection` to parent function too. – Tomasz Jakub Rup Jul 30 '16 at 11:51
  • I am a bit confused about what you mean. Would you elaborate please? Thanks. – darkhorse Jul 30 '16 at 11:56