BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
1.91k stars 201 forks source link

[BUG] before_event not working with validate_on_save = True #894

Open ErikvdVen opened 4 months ago

ErikvdVen commented 4 months ago

I'm using this class to implement the ManifestVersion type in my application: https://python-semver.readthedocs.io/en/latest/advanced/combine-pydantic-and-semver.html

The problem is that Beanie saves this value as an array in the database and when loading the document from the database, it is not able to convert it back, ie. it's not able to load that document again.

I fixed this by triggering the @before_event decorator, though not ideal, it works. But, it doesn't work when validate_on_save=True is set. It seems that validate_on_save is triggered after @before_event.

class UserModel(BeanieDocument):
    name: str
    version: ManifestVersion 

    @before_event(Insert, Replace)
    def semver_to_string(self):
        self.version = str(self.version

    class Settings:
       validate_on_save = True

This wouldn't be an issue for me if there is a possibility to tell Beanie explicitly to convert certain datatypes when inserting/replacing them in the database (after validation). Now it decides that some objects should be an array, while it works better when stored as string.

github-actions[bot] commented 3 months ago

This issue is stale because it has been open 30 days with no activity.

roman-right commented 2 months ago

Hi! Thank you for the report. I'll check it during the next bug fixing session