2010-06-13 49 views
1

我有我需要一個自我引用屬性如下場景:的AppEngine型號SelfReferenceProperty和父子關係

class Post(db.Model): 
    creator = db.UserProperty() 
    post_title = db.StringProperty(required=True) 
    post_status = db.StringProperty(required=True, choices=['draft', 'published']) 
    post_parent = db.SelfReferenceProperty() 

現在,我要確保實體不應該是自己的父母和孩子的實體不能成爲其父母。我如何確保PostForm模型表單和Post模型中的這種關係。

回答

2

我會建議使用ListProperty(db.Key)來代替,存儲祖先列表。這樣一來,就可以查詢更有效(「得到節點x的每一個後代」是比較容易),你可以很容易地執行後一種情況,像這樣:

def ancestor_list_validator(l): 
    if len(l) != len(set(l)): 
    raise Exception("Repeated values in ancestor list!") 

class Post(db.Model): 
    # ... 
    ancestors = db.ListProperty(db.Key, validator=ancestor_list_validator) 

驗證了實體本身的關鍵不在該清單有點困難,並且可能需要編寫一個custom datastore property