nantekkotai achieves

過去記事置き場

Google App Engine DatastoreのListProperty

Google App Engine の Datastore にはなんとリストを格納できるプロパティがある。
以下はサンプル

class Test(db.Model):
    int_list = db.ListProperty(long)      # 数値の場合
    str_list = db.StringListProperty()   # 文字列を扱う場合

# default
int_list = [1,4,5,1432]
str_list = ['Ito','Makoto','was','died.']
test = Test(int_list=int_list, str_list=str_list)
test.put()

key = test.key()
# 先ほど登録したデータを取得
res = Test.get(key)
#きちんと入っているか確認
print res.int_list, res.str_list
# 配列に値を追加する感じで
res.int_list.append(5656)
res.str_list.append(u'nice boat.')
res.put()

res = Test.get(key)
for int_val in res.int_list:
    print int_val
for str_val in res.str_list:
    print str_val

これの結果は、

[1L, 4L, 5L, 1432L] ['Ito', 'Makoto', 'was', 'died.']
1
4
5
1432
5656
Ito
Makoto
was
died.
nice boat.

となる。
int型のリストをそのまま表示すると、大文字のLが後ろにくっつくが、個別に表示させると消えているので問題ないだろう。
たぶんLongのLだと思うのだけど、どうだろうか。
この ListProperty() を使えば、関連するタグとかのIDをまとめてぶっこむことが出来て、より設計をスマートにすることも出来そうだ。
うーん、Google App Engineは奥が深い。