0

I know mongoengine you can set things like unique_with but I want to set a constraint that says "if param_1 is True, param_2 must not be null." Is there a way to do this in mongoengine? Would the best way to handle this be to set conditions in the update/save methods?

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)
Rob
  • 3,333
  • 5
  • 28
  • 71

1 Answers1

1

The easiest way to do this is with 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)
Steve Rossiter
  • 2,624
  • 21
  • 29