__bson__ serialization does not work when Optional / Union used with Custom Types
- Dominant language
- Python
- Stars
- 1.2k
- Forks
- 97
- PR merge metrics
- No merged PRs in 30d
Description
# Bug
_A clear and concise description of what the bug is._
I have a requirement to create a custom type and implement the __bson__ ser method. It works well when used normally, but if used with an Optional / Union , it dosent work. In this case, the internal logic considers the field type as a Union.
### Current Behavior
... _Steps to reproduce the bug_ ...
`class EncryptedString(str):
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v):
if isinstance(v, bytes):
return v.decode("utf-8")
if not isinstance(v, str):
raise TypeError("Only string type is allowed")
return v
@classmethod
def __bson__(cls, v) -> str:
encrypted_data = v.encode("utf-8")
return encrypted_data
class Model1(EmbeddedModel):
key1: Optional[EncryptedString] = None # DOSNT WORK
class EncryptedModel(Model):
encrypted_field: EncryptedString #WORKS WELL
embedded_model: List[Union[Model1]] = [] #DOSNT WORK
non_list_union: Model1`
### Expected behavior
... _A clear and concise description of what you expected to happen._ ...
I expect the __bson__ method to be invoked in every case for a custom type
### Environment
- ODMantic version: 0.9.2
```
...
```
- Version of additional modules (if relevant):
- ...
**Additional context**
_Add any other context about the problem here._
Contributor guide
Research direction
Start with the reproduction models and EncryptedString.__bson__ method shown in the issue, then trace how Optional and Union fields are serialized. Reproduce the failure for both the optional custom field and embedded list, and consider the work done when __bson__ is invoked consistently in each case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- mongodb, python
- Domain
- databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100