gpt4 book ai didi

python - NDB写入是如何计算的?

转载 作者:行者123 更新时间:2023-12-01 04:54:29 24 4
gpt4 key购买 nike

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

例如,我有以下类(class):

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()

它会有效地工作吗? IE。不会写艺术家和标题值,如果它们已经存在并且相同?或者,我应该像下面这样优化代码:

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

最佳答案

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

具体来说,您正在检查if record.artist !=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()

关于python - NDB写入是如何计算的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27748813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com