2012-11-28 32 views
1

好的,這是問題所在。我有這樣的代碼如何添加選擇到谷歌數據存儲StringListProperty?

list_categories = [None,"mathematics","engineering","science","other"] 
class Books(db.Model) 
    title = db.StringProperty(required=True) 
    author = db.StringProperty() 
    isbn = db.StringProperty() 
    categories = db.StringListProperty(default=None, choices = set(list_categories)) 

什麼,我想在這裏做的是有我的book.categories是名單類別的子集,例如 我有一本書,其類別應該是「工程」和「數學」,但當我設置

book.categories = ['engineering','mathematics'] 

它webapp2的給我一個錯誤

BadValueError: Property categories is ['engineering','mathematics']; must be one of set([None,"mathematics","engineering","science","other"]) 

我最初這裏的猜測是,我必須將我的list_choices爲[無「mathemat的POWERSET ics「,」engineering「,」science「,」other「],但效率太低。

有沒有人知道這個解決方法?

回答

2

的原因錯誤(我敢肯定你已經猜到)是StringListProperty不做choices關鍵字參數的任何特殊處理 - 它只是將它傳遞給ListProperty構造,進而將其傳遞到Property構造,在其被評估:

if self.empty(value): 
    if self.required: 
     raise BadValueError('Property %s is required' % self.name) 
    else: 
     if self.choices: 
     match = False 
     for choice in self.choices: 
      if choice == value: 
      match = True 
     if not match: 
      raise BadValueError('Property %s is %r; must be one of %r' % 
           (self.name, value, self.choices)) 

的問題是,它通過每個choice單獨迭代,但它比較它的整個列表(value),這將永遠不會產生因爲比賽字符串不會等於一個列表(再次,你知道這:))。

我的建議是修改你如何爲列表分配屬性。例如,而不是:

book.categories = ['engineering','mathematics'] 

嘗試是這樣的:

for category in ['engineering','mathematics']: 
    book.categories.append(category) 

由於ListProperty包含一個列表,你可以單獨添加的每個項目,使之穿過上述代碼的測試。請注意,爲了讓我的測試能夠正常工作,我必須以稍微不同的方式設置模型 - 但是如果您可以找到上面提到的錯誤,那麼append方法應該可以正常工作。

這使得它不那麼直接,我同意,但它應該繞過上述問題,並希望工作。

0

使用鍵列表創建多對多關係。使用class Book中的categories屬性作爲class Category的密鑰列表。

class Book(db.Model) 
    title = db.StringProperty(required=True) 
    author = db.StringProperty() 
    isbn = db.StringProperty() 

    # List Of Keys 
    categories = db.ListProperty(db.Key) 

class Category(db.Model) 
    name = db.StringProperty(choices = ('science', 'engineering', 'math')) 

有關建模簽出更多的信息和代碼示例:https://developers.google.com/appengine/articles/modeling