问题
I have a model class like:
class Book(ndb.Model):
title = ndb.StringProperty(required=True)
author = ndb.StringProperty(required=True)
and I have some code using this:
book = Book()
print book
>> Book()
book_key = book.put()
>> BadValueError: Entity has uninitialized properties: author, title
Is there a way to check if model is valid before saving it?
And finding out which property is invalid and the type of error (e.g. required). And if you have structured property how will this work then?
Basically looking how to do proper validation of model classes...
回答1:
The approach below does not work!
I run into problems later on. I cannot recall right now what is was.
I have not found an "official" way of doing this. This is my workaround:
class Credentials(ndb.Model):
"""
Login credentials for a bank account.
"""
username = ndb.StringProperty(required=True)
password = ndb.StringProperty(required=True)
def __init__(self, *args, **kwds):
super(Credentials, self).__init__(*args, **kwds)
self._validate() # call my own validation here!
def _validate(self):
"""
Validate all properties and your own model.
"""
for name, prop in self._properties.iteritems():
value = getattr(self, name, None)
prop._do_validate(value)
# Do you own validations at the model level below.
Overload __init__
to call my own _validate
function.
There I call _do_validate
for each property, and eventually a model level validation.
There is a bug opened for this: issue 177.
回答2:
The model is valid, but you have specified that both title
and author
are required. So you have to provide values for these properties every time you write something in.
Basically you are trying to write an empty record.
try:
book = Book()
title = "Programming Google App Engine"
author = "Dan Sanderson"
book_key = book.put()
回答3:
You could try using the validation method that NDB itself uses when it raises the BadValueError
.
book = Book()
book._check_initialized()
This will raise the BadValueError
like when you try to put the entry into the datastore.
来源:https://stackoverflow.com/questions/22081320/how-to-check-if-ndb-model-is-valid