确保价值与mongoengine中的其他价值一起存在

时间:2017-01-04 20:59:37

标签: python mongoengine

我知道mongoengine你可以设置像unique_with这样的东西,但是我想设置一个约束表示"如果param_1为True,则param_2不能为空。"有没有办法在mongoengine做到这一点?处理此问题的最佳方法是在更新/保存方法中设置条件吗?

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)

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用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)