1

I am trying to build a custom JSON Field for Django projects that support MySQL. This is my models:

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:

InterfaceError at /admin/myapp/content/add/

Error binding parameter 2 - probably unsupported type.

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

e4c5
  • 52,766
  • 11
  • 101
  • 134
darkhorse
  • 8,192
  • 21
  • 72
  • 148
  • you are aware that there are several custom JSON packages available already? Though you speak of mysql support your stacktrace shows sqlite?? – e4c5 Jul 30 '16 at 14:21
  • I meant I am going to be using MySQL in production. Right now, the code is in dev. Sorry about the confusion. – darkhorse Jul 30 '16 at 14:55
  • 1
    This error is not one that's produced by django. It comes from lower down, probably the sqlite3 driver. Why don't you log all the fields before calling the super class method in save and update the question with that. – e4c5 Jul 30 '16 at 15:42
  • Can you please elaborate on that, as I am a bit confused. Thanks. – darkhorse Jul 30 '16 at 20:29
  • at the point at which you do ` super(Content, self).save(*args, **kwargs)` just print out self.title, self.data etc – e4c5 Jul 30 '16 at 23:26
  • 1
    Had a similar issue, and realized it was because I was using `sqlite` for development, but the `JSONField` is *postgresql* specific. Using a postgres docker container for development now. – monkut Jul 20 '18 at 03:52

1 Answers1

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.

e4c5
  • 52,766
  • 11
  • 101
  • 134