如何检查NDB模型是否有效

时间:2014-02-27 21:54:24

标签: python google-app-engine app-engine-ndb

我有一个类似的模型类:

class Book(ndb.Model):
    title = ndb.StringProperty(required=True)
    author = ndb.StringProperty(required=True)

我有一些代码使用它:

    book = Book()
    print book
    >> Book()
    book_key = book.put()
    >> BadValueError: Entity has uninitialized properties: author, title

有没有办法在保存之前检查模型是否有效?

找出哪个属性无效以及错误类型(例如必需)。 如果你有结构化财产,那么它将如何运作呢?

基本上了解如何正确验证模型类......

3 个答案:

答案 0 :(得分:2)

以下方法不起作用!
我后来遇到了问题。我现在不记得是什么。


我还没有找到这样做的“官方”方式。 这是我的解决方法:

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,最后进行模型级验证。

为此打开了一个错误:issue 177

答案 1 :(得分:0)

该模型有效,但您已指定需要titleauthor。因此,每次写入内容时都必须为这些属性提供值。 基本上你是想写一个空记录。

尝试:

book = Book()
title = "Programming Google App Engine"
author = "Dan Sanderson"
book_key = book.put()

答案 2 :(得分:0)

您可以尝试使用NDB在提升BadValueError时使用的验证方法。

book = Book()
book._check_initialized()

当您尝试将条目放入数据存储区时,这会引发BadValueError

相关问题