您实际上无法将真正的字典存储为 ListProperty 中的类型(它仅支持数据存储属性类型,dict 不是其中之一),因此您将无法获得您正在寻找的行为。所有数据是否都相同(即每个元素代表一个单词分数)?假设将每个单词作为其自己的属性存储在模型上是没有意义的,一个“肮脏”的解决方案是创建一个str 类型的ListProperty,然后将单词和分数作为单独的元素附加。然后,当您在列表中搜索一个单词时,您将返回该单词索引位置的值 + 1。这看起来像:
class MyEntity(db.Model):
name = db.StringProperty()
description = db.TextProperty()
word_list = db.ListProperty()
然后你可以添加类似的词:
new_entity = MyEntity()
new_entity.word_list = ['word1', 1, 'word2', 2, 'word3', 10]
然后您可以查询特定实体,然后检查其word_list 属性(一个列表),查找您的目标词并将元素返回到它后面的一个位置。
更复杂的建议
但是,如果这不是一个选项,您可以考虑创建另一个看起来像这样的模型(比如说WordScore):
class WordScore(db.Model):
word = db.StringProperty()
score = db.IntegerProperty()
然后,当您需要添加新分数时,您将创建一个WordScore 实例,填写属性,然后将其分配给适当的实体。我还没有测试过这些,但想法是这样的:
# Pull the 'other' entity (this would be your main class as defined above)
q = OtherEntity.all()
q.filter('name =', 'Someone')
my_entity = q.get()
# Create new score
ws = WordScore(parent=my_entity)
ws.word = 'dog'
ws.score = 2
ws.put()
然后,您可以通过执行类似操作(同样,目前完全未经测试 - 请注意 :))为“某人”提取 dog 的分数:
# Get key of 'Someone'
q = OtherEntity.all()
q.filter('name =', 'Someone')
my_entity = q.get().key()
# Now get the score
ws = WordScore.all()
ws.filter('word = ', 'dog').ancestor(my_entity)
word_score = ws.get().score