umongo
umongo copied to clipboard
Is there a way to modify a field when initialization?
@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?
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.
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?
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?
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,...