Default dict value in JSONField causes non-valid JSON string stored in db.
See original GitHub issueI 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:
- Created 9 years ago
- Comments:11 (6 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I found a workaround. Doing a
json.dumps
gets rid of the issue.My dict was like:
I stored it as valid json by:
Remove the
json.dumps
it gets stored as:which is invalid
Fixed in 6912356, as @nebril suggested. Thank you all for the report!