umongo icon indicating copy to clipboard operation
umongo copied to clipboard

Is there a way to modify a field when initialization?

Open tobeczm opened this issue 4 years ago • 4 comments

@instance.register
class User(Document):
    login = fields.StringField(unique=True)
    password = fields.StringField()

    class Meta:
        collection_name = "user"


 user = User(login = 'test', password='123')
 print(user.password)
 # the output should be a hash like 'sfjeijaojfeaxif1u34ipri32er'

how to modify the User class to achieve that?

tobeczm avatar Jul 01 '20 14:07 tobeczm

You could override __init__ to do the hashing there, I suppose.

My preference for this use case is to add a dedicated setter method for password and call it after init.

lafrech avatar Jul 01 '20 15:07 lafrech

You could override __init__ to do the hashing there, I suppose.

My preference for this use case is to add a dedicated setter method for password and call it after init.

Thanks, but it seems not working. Could you show me an example?

tobeczm avatar Jul 02 '20 16:07 tobeczm

The problem is when loading an instance of User from the database, the fields for login and password will not be set til after the init call is over. This is a problem if I want to initialize other constants that depend on the value of fields coming from the database.

Is there some kind of post-init-hook I could implement?

molten-firescar96 avatar Aug 04 '20 17:08 molten-firescar96

Indeed the same schema load happens when loading from base and at init.

You could use a post_load hook (see marchmallow docs) but it would be executed in both cases. If this is not intended, then I guess you're out of luck and need to do stuff manually. A solution to this would be to add hooks like pre_from_mongo, post_from_mongo,...

lafrech avatar Oct 12 '20 12:10 lafrech