Search code examples
pythondjangodjango-fixturesloaddatadumpdata

Django dumpdata-loaddata error serializing custom class: ' Syntax error near "F" '


I'm trying to create a set of fixtures from my database using the dumpdata command provided by Django. I want to be able to load these fixtures using the loaddata command.

One of the Models I'm trying to dump has a custom field: particularly, I'm facing my problem with a field (of type MyHStoreField) that inherits from django.HStoreField. Django is incapable of serializing MyHStoreField.

django.db.utils.InternalError: Problem installing fixture '/fixture_files/fixture.json':
   Could not load MyModel: Syntax error near "F" at position 12
LINE 1: ...a_model_field" = '0.0000000000000000', "my_hstore_field" = '{"blabla...

From the Django docs, I think that what this class needs in order to be serialized is a custom JSONEncoder (https://docs.djangoproject.com/en/2.2/topics/serialization/#json-1). However, I don't know how to tell both dumpdata and loaddata to use this Encoder.

Is there any kind of registry that django uses in order to know which Encoders are available, or do I need to override the loaddata and dumpdata commands somehow?


Solution

  • I found out that the problem was serializing the object, since in the file it has the wrong format:

    "my_hstore_field": "{\"blabla\": false}"
    

    which is not a valid json but a string with a json format that Django doesn't know how to deserialize.

    The solution has been postprocessing the file using a script just after running dumpdata, and saving that field as valid json:

    "my_hstore_field": {"blabla": false}