Search code examples
pythonvalidationgoogle-app-enginegoogle-cloud-datastoreapp-engine-ndb

Python NDB: Property validation in queries?


I have a model:

def category_path_validator(prop , val):
    # makes sure the path is of the form `first.second(...)last`
    # and that it represents a valid path in the category tree.
    pass

class Product(ndb.Model):
    category_path = nsb.StringProperty(validator=category_path_validator)

I want to be able to get all Products within a category so my query is:

Product.Query(ndb.AND(Product.category_path >= 'furniture' , Product.category_path <= 'furniturez'))

(adding the z works since <=,>= compares strings lexicography )

now this produces an error because furniturez is not a valid category.

Is there a way to query the value without validation , but still be able to set the property with validation ?


Solution

  • I think the best way is to split the validation into two parts. The first part is to simplify your validator to only check the StringProperty:

    def category_path_validator(prop , val):
        # makes sure the path is of the form `first.second(...)last`
        pass
    

    The second part is to add a Model hook:

    def _pre_put_hook(self):
        # makes sure that category_path represents a valid path in the category tree.
        pass
    

    The downside is that you won't know if the category_path is bad until you try and put() it.