【问题标题】:Nested comments in gae/pythongae/python 中的嵌套注释
【发布时间】:2012-10-11 18:17:03
【问题描述】:

我是 GAE 和 python 的新手。挑战在于制作具有例如 3 级标识的嵌套 cmets。 GAE-datastore 为我们做了一半的工作。它以所需的方式存储和输出嵌套结构。 所以让例子非常简单:

  • 父 1
    • 父 1 的子 1
    • 父 1 的子 2
      • 孩子 2 的孩子 1
      • 孩子 2 的孩子 2
  • 父 2
    • 父母 2 的孩子 1
      • 孩子 1 的孩子 1
    • 父 2 的子 2
      • 孩子 2 的孩子 1

如果我们将这个层次结构保留在数据存储中(通过在创建实体时正确使用属性“父”),我们将能够获取已经以这种方式排序的实体列表:
家长 1
父母 1 的孩子 1
父母 1 的孩子 2
孩子 2 的孩子 1
孩子 2 的孩子 2
家长 2
父母 2 的孩子 1
孩子 1 的孩子 1
父母 2 的孩子 2
孩子 2 的孩子 1

所以我们只需要做出正确的识别。换句话说,我们需要为每个项目传递一个参数给我们的模板。让我们将此参数称为 0,1,2。我有解决方案,但我不喜欢它。 我这样计算 ident 参数的值:

ident_value = len(CURREN_ITEM.key().to_path())/2 - 2

(GAE 层次结构路径中的每一层由 2 个元素组成。)

所以在从数据存储中获取模型后,这个循环正在执行:

for model in model_list:            
    new_model_list.append(model) # helper list
    ident_value = len(model.key().to_path())/2 - 2 
    if ident_value>3: ident_value = 3 # max ident = 3
    setattr(new_model_list[i], 'ident', ident_value )
    i += 1  

然后 new_model_list 被传递给 jinja 模板,其中每个项目的类名是根据 model.ident 值分配的。 需要帮助列表,因为模型是 MyModel 类的实例,用于将数据保存在数据存储中并且没有“ident”属性。

所以问题是:有没有更优雅的方式来做同样的事情?

【问题讨论】:

    标签: python google-cloud-datastore


    【解决方案1】:

    如果有人需要我的解决方案:

    def nest (flow, root_rep_id_list, deep = 0): 
        msglist = []
        nested_comments = []
        deep += 1 
    
        for rep_id in root_rep_id_list:
            if rep_id in flow:
                msglist.append(flow[rep_id])        
    
        for msg in msglist: 
            nested_comments.append(Nestedobject (msg, nest(flow, msg.replies, deep) if msg.replies else None, deep))
            logging.error(msg.replies)      
        return nested_comments
    

    【讨论】:

      猜你喜欢
      • 2015-01-27
      • 2011-07-12
      • 2011-10-11
      • 2010-11-22
      • 2014-10-12
      • 1970-01-01
      • 2013-08-11
      • 2012-01-17
      • 1970-01-01
      相关资源
      最近更新 更多