Serialization

Data in Redis

pydantic-aioredis uses Redis Hashes to store data. The `_primary_key_field` of each Model is used as the key of the hash.

Because Redis only supports string values as the fields of a hash, data types have to be serialized.

Simple data types

Simple python datatypes that can be represented as a string and natively converted by pydantic are converted to strings and stored. Examples are ints, floats, strs, bools, and Nonetypes.

Unintentional Type Casting with Union Types

When using Union types, pydantic will cast the value to the first type in the Union. This can cause unintended type casting. For example, if you have a field of type Union[float, int], and you set the value to 1, pydantic will cast the value to a float 1.0. In the other direction (i.e. x: Union[int, float]) will result in the value being casted as an int and rounded. If you used a value of x = 1.99, it would get cast as an int and rounded to 1.

This is an issue with Pydantic. More info can be found in this issue reported by david-wahlstedt and this issue in Pydantic.

There are some test cases in pydantic_aioredis that illustrate this problem.

Complex data types

Complex data types are dumped to json with json.dumps().

Custom serialization is possible using json_default and json_object_hook.

These methods are part of the abstract model and can be overridden in your model to dump custom objects to json and then back to objects. An example is available in examples