我正在尝试使用MongoEngine进行一个项目而且非常好。我想知道是否可以为另一个字段中的字段设置默认值?像这样的东西
import mongoengine as me
class Company(me.Document):
short_name = me.StringField(required=True)
full_name = me.StringField(required=True, default=short_name)
此操作失败并显示错误ValidationError (Company:None) (StringField only accepts string values: ['full_name'])
:编辑:
我没有提到我的应用程序有一个服务层,这使我能够像这样简单地执行:
if company_data['short_name'] is None:
myCompany.full_name = company_data['short_name']
obj = myCompany.save()
并且效果很好。
答案 0 :(得分:5)
您可以在Document
上覆盖save()
方法:
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)
答案 1 :(得分:0)
看看http://docs.mongoengine.org/guide/defining-documents.html#field-arguments:
您可以通过将函数传递给字段的默认属性来实现此目的:
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])