2014-02-27 31 views
1

我有一个模型类,如:如何检查是否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 

有没有一种方法来检查,如果模型是有效的保存之前?

并找出哪些属性无效和错误的类型(如需要)。 如果你有结构化财产,那么这项工作将如何呢?

基本上看怎么办模型类的适当的验证......

+1

我认为保存之前应该也去标题,如果这很重要..因为否则你可以简单'尝试/ except'我猜.. – Lipis

+0

重复:看看Guido的答案:http://stackoverflow.com/问题/ 15200952/appengine-ndb-property-validations – voscausa

+0

@voscausa由同一个OP :) – Lipis

回答

0

的模型是有效的,但你已经指定了两个titleauthor是必需的。因此,每次写入内容时,必须为这些属性提供值。 基本上,您正在尝试写入空记录。

尝试:

book = Book() 
title = "Programming Google App Engine" 
author = "Dan Sanderson" 
book_key = book.put() 
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

0

您可以尝试使用NDB自身在引发BadValueError时使用的验证方法。

book = Book() 
book._check_initialized() 

这会引发BadValueError,就像您尝试将条目放入数据存储区时一样。