2014-02-27 34 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,就像您嘗試將條目放入數據存儲區時一樣。