【问题标题】:Google App Engine fetch() and printGoogle App Engine fetch() 和打印
【发布时间】:2010-10-30 22:20:43
【问题描述】:

这是模型:

class Rep(db.Model):
    author = db.UserProperty()
    replist = db.ListProperty(str)
    unique = db.ListProperty(str)
    date = db.DateTimeProperty(auto_now_add=True)

我正在将replist 写入数据存储区:

        L = []
        rep = Rep()
        s = self.request.get('sentence')   
        L.append(s)

        rep.replist = L
        rep.put()

并检索

mylist = rep.all().fetch(1)

我假设mylist 是一个列表。我如何打印它的元素?当我尝试它时,我最终得到了这个对象;类似[<__main__.Rep object at 0x04593C30>]

谢谢!

编辑

@Wooble:我也使用模板。我不明白的是;我像这样打印列表L:

% for i in range(len(L)):
<tr>
  <td>${L[i]}</td>
</tr>
% endfor

这很有效。但是mylist 同样的事情不起作用。我试图用T = type(mylist) 获得mylist 的类型也不起作用。

【问题讨论】:

    标签: google-app-engine google-cloud-datastore


    【解决方案1】:

    如果您使用fetch(1),您将获得一个包含 1 个元素的列表(或 None,如果没有要获取的实体)。

    通常,要打印实体列表中每个实体的所有元素,您可以执行以下操作:

    props = Rep.properties().keys()
    for myentity in mylist:
         for prop in props:
             print "%s: %s" % (prop, getattr(myentity, prop))
    

    虽然大多数人只是使用模板以某种方式显示实体的数据。

    【讨论】:

    • 谢谢,我不明白第一行。但请参阅上面的编辑。
    【解决方案2】:

    rep.all().fetch(1) 的结果是一个对象。您将需要像这样迭代:

    {% for i in mylist %}
    <tr>
      <td>{{i.author }}</td>
      ...
    </tr>
    {% endfor %}
    

    如果要打印 i.replist(list),可以使用 Django 的模板函数 join eg:

    {% for i in mylist %}
      <tr>
        <td>{{i.replist|join:"</td><td>" }}</td>
      </tr>
    {% endfor %}
    

    【讨论】:

    • 谢谢。至少现在我没有收到错误消息,但我收到了None。而且我不明白为什么我必须使用i.author?我以为我将字符串s 的内容存储在L 和mylist 中。然后,如果我获取这些列表之一;它们应该包含s 的内容。但这并没有发生。有什么建议吗?
    • 你知道如何用 Mako 模板获得同样的效果吗stackoverflow.com/questions/4061673/…
    猜你喜欢
    • 2013-05-18
    • 2023-03-18
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多