mongoengine default value from another field

mongoengine, python

Solution

You can override `save()` method on a `Document`:

class Company(me.Document):
    short_name = me.StringField(required=True)
    full_name = me.StringField()

    def save(self, *args, **kwargs):
        if not self.full_name:
            self.full_name = self.short_name

        return super(Company, self).save(*args, **kwargs)

Problem

I'm trying out MongoEngine for a project and its quite good. I was wondering if it is possible to set a default value for a field from another field? Something like this ``` import mongoengine as me class Company(me.Document): short_name = me.StringField(required=True) full_name = me.StringField(required=True, default=short_name) ``` this fails with an error `ValidationError (Company:None) (StringField only accepts string values: ['full_name'])` :EDIT: I did not mention that my app has a service layer which enabled me to simply do it like this: ``` if company_data['short_name'] is None: myCompany.full_name = company_data['short_name'] obj = myCompany.save() ``` and it works quite nicely.

Original source