Search code examples
djangopostgresqldjango-modelsdjango-jsonfield

How to correctly deserialize datetime objects stored in JSONField with DjangoJSONEncoder?


I'm storing datetime objects in a JSONField with Django 2.1 and a PostgreSQL, but I can't find a way to correctly deserialize them when querying database :

I've tried to use DjangoJSONEncoder which works correctly for serialization. But deserialization does'nt work properly

class Book(models.Model):
    data = JSONField(encoder=DjangoJSONEncoder)


class BookTest(TestCase):
    def test_JSONField_deserialize(self):
        # record it in PostgreSQL Database :
        instance = Book.objects.create(data=
                                       {'date': tz.now()}
                                       )
        # Retrieve it from PostgreSQL Database :
        result = Book.objects.get(id=instance.id)
        # Test the type :
        self.assertEqual(type(result.data['date']), datetime)
AssertionError: <class 'str'> != <class 'datetime.datetime'>

What am I doing wrong ? Do I need to extends DjangoJSONEncoder, or provide a .from_db_value() custom method ?


Solution

  • Actually, I think this post answer well the question.

    By serializing into JSON, the dates/times format is loosed, and build a decoder would structurally mean accepting the risk of false positive.