diff --git a/aredis_om/model/model.py b/aredis_om/model/model.py index e45e3939..377ededb 100644 --- a/aredis_om/model/model.py +++ b/aredis_om/model/model.py @@ -1695,6 +1695,9 @@ async def save( self.check() db = self._get_db(pipeline) document = jsonable_encoder(self.dict()) + + # filter out values which are `None` because they are not valid in a HSET + document = {k: v for k, v in document.items() if v is not None} # TODO: Wrap any Redis response errors in a custom exception? await db.hset(self.key(), mapping=document) return self diff --git a/tests/test_hash_model.py b/tests/test_hash_model.py index 1870ec3d..c9673585 100644 --- a/tests/test_hash_model.py +++ b/tests/test_hash_model.py @@ -878,6 +878,26 @@ async def test_xfix_queries(members, m): @py_test_mark_asyncio +async def test_none(): + class ModelWithNoneDefault(HashModel): + test: Optional[str] = Field(index=True, default=None) + + class ModelWithStringDefault(HashModel): + test: Optional[str] = Field(index=True, default="None") + + await Migrator().run() + + a = ModelWithNoneDefault() + await a.save() + res = await ModelWithNoneDefault.find(ModelWithNoneDefault.pk == a.pk).first() + assert res.test is None + + b = ModelWithStringDefault() + await b.save() + res = await ModelWithStringDefault.find(ModelWithStringDefault.pk == b.pk).first() + assert res.test == "None" + + async def test_update_validation(): class TestUpdate(HashModel): name: str diff --git a/tests/test_json_model.py b/tests/test_json_model.py index b1950b6e..84649202 100644 --- a/tests/test_json_model.py +++ b/tests/test_json_model.py @@ -974,6 +974,26 @@ async def test_xfix_queries(m): @py_test_mark_asyncio +async def test_none(): + class ModelWithNoneDefault(JsonModel): + test: Optional[str] = Field(index=True, default=None) + + class ModelWithStringDefault(JsonModel): + test: Optional[str] = Field(index=True, default="None") + + await Migrator().run() + + a = ModelWithNoneDefault() + await a.save() + res = await ModelWithNoneDefault.find(ModelWithNoneDefault.pk == a.pk).first() + assert res.test is None + + b = ModelWithStringDefault() + await b.save() + res = await ModelWithStringDefault.find(ModelWithStringDefault.pk == b.pk).first() + assert res.test == "None" + + async def test_update_validation(): class Embedded(EmbeddedJsonModel):