Python 如何计算NDB写入?

Python 如何计算NDB写入?,python,google-app-engine,google-cloud-datastore,app-engine-ndb,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_

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

例如,我有以下课程:

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


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

事实上,根据您所使用的索引,写操作可能不止一次

如果你看一下,你可能会有更多的信息,是的,你应该优化——你只是做错了

具体来说,您正在检查
if record.artist!=艺术家
&c)在你的片段之后

if record.artist != artist: # new line!
    record.artist = artist
这当然确保了
=条件无法持续。因此,您永远不会达到可以调用
.put()
的条件

试着,而不是像这样:

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

谢谢我的第二个代码有什么问题?在你的代码中,当只有标题被更改时,你会同时更新标题和艺术家-这是正确的方法吗?@lauz补充道:首先你要确保
记录。艺术家
等于
艺术家
(如果有必要,通过分配它),然后你检查他们是否仍然不同(当然不会是这样:你的作业只是确保了!)既然不是这样,你就不会调用
put
。至于分配
record
的两个字段,即使在只需要一个字段的情况下,这也是微不足道的(纳秒)内存操作——我选择它只是为了简化一点,保留一个bool标志,而不是两个,并保持它的对称性。我现在看到了我的错误,谢谢。关于在只更改一个时分配
记录的两个字段,这会不会导致我试图避免的额外写入操作?@LA_uu不,它不会,当调用
put
时,会发生唯一的写入操作。你确定吗?我们正在讨论NDB写入操作,不要相信它只是一个操作-
def add_song(artist, title):
    song_id = artist+ ' - ' + title
    record = Song.get_by_id(song_id)
    if record:
        if record.artist != artist or record.title != title: # new line!
            record.artist = artist
            record.title = title
            is_new = True
        else:
            is_new = False
    else:
        record = Song(id=song_id, artist=artist, title=title)
        is_new = True
    if is_new:
         record.put()