BeanieODM / beanie

Asynchronous Python ODM for MongoDB

Home Page:http://beanie-odm.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[BUG] before_event not working with validate_on_save = True

ErikvdVen opened this issue · comments

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.

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

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