如何检查NDB模型是否有效 [英] How to check if NDB model is valid

查看:142
本文介绍了如何检查NDB模型是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的模型类:

I have a model class like:

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

是否可以在保存模型之前检查模型是否有效?

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.

为此打开了一个错误:

There is a bug opened for this: issue 177.

这篇关于如何检查NDB模型是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆