How can I execute some code only when a document is created in mongoengine, not when updated.
class Account(Document):
name = StringField(max_length=80, default=None)
username = StringField(max_length=60, required=True)
created_at = DateTimeField(default=datetime.now(), required=True)
updated_at = DateTimeField(default=datetime.now(), required=True)
meta = {
'collection': 'accounts'
}
Now I want to generate random username and assign it to the username field before a document is created.
Any help is appreciated. Thanks.
You should use one of the MongoEngine's signals -
pre_save()
sounds like a good fit. There are different ways to attach an event handler to a signal, here is one of them: