确保值与 mongoengine 中的其他值存在
making sure value exists with other value in mongoengine
我知道 mongoengine 你可以设置 unique_with
之类的东西,但我想设置一个约束 "if param_1 is True, param_2 must not be null." 有没有办法在 mongoengine 中做到这一点?处理此问题的最佳方法是在 update/save 方法中设置条件吗?
class Doc(Document):
param_1 = BooleanField()
param_2 = StringField()
def save(self, *args, **kwargs):
# DO SOMETHING HERE TO MAKE SURE
# IF param_1 == True, param_2 != None
super(Doc, self).save(*args, **kwargs)
最简单的方法是使用 signals。
class Doc(Document):
param_1 = BooleanField()
param_2 = StringField()
@classmethod
def pre_save(cls, sender, document, **kwargs):
if (document.param_1 is True) and (document.param_2 is None):
raise ValueError("If param_1 is True then param_2 cannot be None")
signals.pre_save.connect(Document.pre_save, sender=Document)
我知道 mongoengine 你可以设置 unique_with
之类的东西,但我想设置一个约束 "if param_1 is True, param_2 must not be null." 有没有办法在 mongoengine 中做到这一点?处理此问题的最佳方法是在 update/save 方法中设置条件吗?
class Doc(Document):
param_1 = BooleanField()
param_2 = StringField()
def save(self, *args, **kwargs):
# DO SOMETHING HERE TO MAKE SURE
# IF param_1 == True, param_2 != None
super(Doc, self).save(*args, **kwargs)
最简单的方法是使用 signals。
class Doc(Document):
param_1 = BooleanField()
param_2 = StringField()
@classmethod
def pre_save(cls, sender, document, **kwargs):
if (document.param_1 is True) and (document.param_2 is None):
raise ValueError("If param_1 is True then param_2 cannot be None")
signals.pre_save.connect(Document.pre_save, sender=Document)