如果我第二次将相同的数据添加到数据存储区,是否需要额外的写入操作?
例如,我有以下课程:
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
答案 0 :(得分:1)
答案 1 :(得分:1)
是的,你应该优化 - 你只是做错了。
具体来说,您正在检查<{1}}&amp; c) 您的代码段之后
if record.artist != artist
当然可以确保if record.artist != artist: # new line!
record.artist = artist
条件不会持续存在。因此,您永远不会达到可以调用!=
的条件。
尝试,比如:
.put()