代码之家  ›  专栏  ›  技术社区  ›  GeekTantra

Appengine模型自引用属性与亲子关系

  •  1
  • GeekTantra  · 技术社区  · 14 年前

    我有一个场景,其中我需要一个自引用属性,如下所示:

    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模型中的这种关系。

    1 回复  |  直到 14 年前
        1
  •  2
  •   Nick Johnson    14 年前

    我建议改为使用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