mongoengine default value from another field

谁都会走 提交于 2019-12-11 04:15:48

问题


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.


回答1:


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)



回答2:


Take a look at http://docs.mongoengine.org/guide/defining-documents.html#field-arguments:

You can achieve this by passing a function to default property of the field:

class ExampleFirst(Document):
    # Default an empty list
    values = ListField(IntField(), default=list)

class ExampleSecond(Document):
    # Default a set of values
    values = ListField(IntField(), default=lambda: [1,2,3])

class ExampleDangerous(Document):
    # This can make an .append call to  add values to the default (and all the following objects),
    # instead to just an object
    values = ListField(IntField(), default=[1,2,3])


来源:https://stackoverflow.com/questions/24045429/mongoengine-default-value-from-another-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!