question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Default dict value in JSONField causes non-valid JSON string stored in db.

See original GitHub issue

I have a model with JSONField with default value set to constant dict value.

The default value was stored in db as non-valid json.

I was able to work around this by changing this line (in my model): visual_config = JSONField(default=DEFAULT_PARAMETERS['visual_config'], blank=False, null=False) With this: visual_config = JSONField(default=lambda: CustomerConfig.DEFAULT_PARAMETERS['visual_config'], blank=False, null=False)

Notice that I added default value as lambda function.

This is caused by django default Field.get_default method, which runs force_text method on the default value if it is not callable:

def get_default(self):
        """
        Returns the default value for this field.
        """
        if self.has_default():
            if callable(self.default):
                return self.default()
            return force_text(self.default, strings_only=True)
        if (not self.empty_strings_allowed or (self.null and
                   not connection.features.interprets_empty_strings_as_nulls)):
            return None
        return ""

My idea for a fix would be to override the get_default method in JSONField.

Cheers, Maciej

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:11 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
ketanbhattcommented, Sep 8, 2015

I found a workaround. Doing a json.dumps gets rid of the issue.

My dict was like:

mydic = { "key": "value"}

I stored it as valid json by:

class NotificationTemplate(models.Model):
    extra = JSONField(default=json.dumps(NOTIFICATION_TEMPLATE_EXTRA)))

Remove the json.dumps it gets stored as:

{ 'key': 'value'}

which is invalid

0reactions
skorokithakiscommented, Sep 8, 2015

Fixed in 6912356, as @nebril suggested. Thank you all for the report!

Read more comments on GitHub >

github_iconTop Results From Across the Web

27538 (Value of JSONField is being re-encoded to string even ...
I have the same problem, Re-json the JSONField value. from django.contrib.postgres.fields import JSONField class Foo(models.Model): photos = JSONFields( ...
Read more >
Django djsonfield Decimal stored as string in expressions
I have a JSONField with some financial data.
Read more >
MySQL 8.0 Reference Manual :: 11.5 The JSON Data Type
MySQL parses any string used in a context that requires a JSON value, and produces an error if it is not valid as...
Read more >
JSON Functions And Operators - SQLite
SQLite text values can be understood as JSON objects, arrays, or strings. If an SQLite text value that is not a well-formed JSON...
Read more >
Loading JSON data from Cloud Storage | BigQuery
You are subject to the following limitations when you load data into BigQuery from a Cloud Storage bucket: If your dataset's location is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found