问题描述
我有一个模型类,如:
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...
推荐答案
下面的方法不行!
我后来遇到了问题.我现在想不起来是什么了.
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.
重载 __init__
以调用我自己的 _validate
函数.在那里我为每个属性调用 _do_validate
,并最终进行模型级验证.
Overload __init__
to call my own _validate
function.There I call _do_validate
for each property, and eventually a model level validation.
为此打开了一个错误:issue 177.
There is a bug opened for this: issue 177.
这篇关于如何检查 NDB 模型是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!