如何计算NDB写入?

时间:2015-01-02 21:31:58

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

如果我第二次将相同的数据添加到数据存储区,是否需要额外的写入操作?

例如,我有以下课程:

class Song(ndb.Model):
    artist = ndb.StringProperty(required=True, indexed=True)
    title = ndb.StringProperty(required=True, indexed=False)

和以下代码在那里添加新歌或更新现有值:

def add_song(artist, title):
    song_id = artist+ ' - ' + title
    record = Song.get_by_id(song_id)
    if not record:
        record = Song(id=song_id)
    record.artist = artist
    record.title = title
    record.put()

它会有效吗?即不会写艺术家和标题值,如果他们已经存在并且相同吗?或者,我应该如下优化代码:

def add_song(artist, title):
    song_id = artist+ ' - ' + title
    record = Song.get_by_id(song_id)
    if not record:
        record = Song(id=song_id)
    if record.artist != artist: # new line!
        record.artist = artist
    if record.title != title: # new line!
        record.title = title
    if record.artist != artist or record.title != title: # new line!
        record.put()

这两个代码在调用时会产生相同数量的写操作:

add_song('Artist Name', 'Song Title')
add_song('Artist Name', 'Song Title') # same artist, same title - second addition

add_song('Artist Name', 'Song Title')
add_song('Artist Name', 'New Song Title') # same artist, new title - second addition

2 个答案:

答案 0 :(得分:1)

是的,重新放置完全相同的对象将导致写入数据存储区。

实际上,根据您所使用的索引,可能会多于一次写入。

如果查看ndb docthis article

,您可能会获得更多信息

答案 1 :(得分:1)

是的,你应该优化 - 你只是做错了。

具体来说,您正在检查<{1}}&amp; c) 您的代码段之后

if record.artist != artist

当然可以确保if record.artist != artist: # new line! record.artist = artist 条件不会持续存在。因此,您永远不会达到可以调用!=的条件。

尝试,比如:

.put()