Gray sky, Blue sea.

programing, book, photo

gae - ndb.StructurdPropertyでJava Beanチックなエンティティ作成

 データストアの非同期処理用に追加された(?)ndb.Modelはメンバに構造体っぽいのを保存できる。

(main.py)

from google.appengine.ext import ndb 

class Bean(ndb.Model):
    id = ndb.IntegerProperty()
    dt = ndb.DateProperty(auto_now=True)

class Hoge(ndb.Model):
    name = ndb.StringProperty()
    bean = ndb.StructuredProperty(Bean)

class Test(webapp.RequestHandler):
    def get(self):
        # 中身
        b = Bean()
        b.id = 456 
        # 親
        h = Hoge()
        h.name = "hige"
        h.bean = b 
        h.put()

        # ndbではall()は使えない。query()を使用。
        #hoges = Hoge.all()
        hoges = Hoge.query()
        template_values = { 
            'hoges' : hoges,
        }   
        path = os.path.join(os.path.dirname(__file__), 'test.html')
        self.response.out.write(template.render(path, template_values))

djangoのタグでは、hoge.bean.id、というように"."でつないで参照。

(test.html)

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        {% if hoges %}
            {% for item in hoges %}
            {{ item.name }}, {{ item.bean.id }}, {{ item.bean.dt }} <br>
            {% endfor %}
        {% endif %}
    </body>
</html>

gaeのdatastore-viewerではこんな感じで表示される。↓

f:id:h_maz:20120310172309p:plain 

classが格納されるというよりは、classのメンバが展開されて格納されたような感じ。