Skip to content

Commit 6493750

Browse files
committed
Add serialize_class attribute to support using custom Serializer
1 parent 4092862 commit 6493750

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ this mixin definitely suits you.
1111
- [Advanced usage](#Advanced-usage)
1212
- [Custom formats](#Custom-formats)
1313
- [Custom types](#Custom-types)
14+
- [Custom Serializer](#Custom-serializer)
1415
- [Timezones](#Timezones)
1516
- [Troubleshooting](#Troubleshooting)
1617
- [Tests](#Tests)
@@ -304,6 +305,27 @@ Unfortunately you can not access formats or tzinfo in that functions.
304305
I'll implement this logic later if any of users needs it.
305306

306307

308+
# Custom Serializer
309+
To have full control over the Serializer, you can define your own subclass with custom logic, and then configure the mixin to use it.
310+
```python
311+
from sqlalchemy_serializer import Serializer, SerializerMixin
312+
313+
314+
class CustomSerializer(Serializer):
315+
316+
def serialize_model(self, value) -> dict:
317+
"""Custom override adding special case for a complex model."""
318+
if isinstance(value, ComplexModel):
319+
return complex_logic(value)
320+
return super().serialize_model(value)
321+
322+
323+
class CustomSerializerMixin(SerializerMixin):
324+
325+
serialize_class = CustomSerializer
326+
```
327+
328+
307329
# Timezones
308330
To keep `datetimes` consistent its better to store it in the database normalized to **UTC**.
309331
But when you return response, sometimes (mostly in web, mobile applications can do it themselves)

sqlalchemy_serializer/serializer.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def fork(self, key: str) -> "Serializer":
123123
Return new serializer for a key
124124
:return: serializer
125125
"""
126-
serializer = Serializer(**self.opts._asdict())
126+
serializer = self.__class__(**self.opts._asdict())
127127
serializer.set_serialization_depth(self.serialization_depth + 1)
128128
serializer.schema = self.schema.fork(key=key)
129129

@@ -233,6 +233,9 @@ class SerializerMixin:
233233
some extra serialization logic
234234
"""
235235

236+
# Default Serializer class
237+
serialize_class: Serializer = Serializer
238+
236239
# Default exclusive schema.
237240
# If left blank, serializer becomes greedy and takes all SQLAlchemy-model's attributes
238241
serialize_only: tuple = ()
@@ -292,7 +295,7 @@ def to_dict(
292295
:param tzinfo: datetime.tzinfo converts datetimes to local user timezone
293296
:return: data: dict
294297
"""
295-
s = Serializer(
298+
s = self.serialize_class(
296299
date_format=date_format or self.date_format,
297300
datetime_format=datetime_format or self.datetime_format,
298301
time_format=time_format or self.time_format,

0 commit comments

Comments
 (0)