gpt4 book ai didi

google-app-engine - 如何在 Google 应用引擎数据库中过滤具有空引用的行

转载 作者:太空宇宙 更新时间:2023-11-03 15:31:49 27 4
gpt4 key购买 nike

我有一个模型 UnitPattern,它引用了另一个模型 UnitPatternSet

例如

class UnitPattern(db.Model):
unit_pattern_set = db.ReferenceProperty(UnitPatternSet)

在我看来,我想将所有具有 unit_pattern_set refrences 的 UnitPatterns 显示为 None,但是查询 UnitPattern.all().filter("unit_pattern_set =", None) 不返回任何内容,尽管我总共有 5 个 UnitPatterns,其中 2 个有'unit_pattern_set' 集和 3 没有

例如

print 'Total',UnitPattern.all().count()
print 'ref set',UnitPattern.all().filter("unit_pattern_set !=", None).count()
print 'ref not set',UnitPattern.all().filter("unit_pattern_set =", None).count()

输出:

Total 5
ref set 2
ref not set 0

查询 2 和查询 3 的总和不应该等于查询 1 吗?

原因似乎是我后来添加了引用属性unit_pattern_set,而这些UnitPattern对象在此之前就存在了,但是我该如何过滤这些实体呢?

最佳答案

这在 docs 中有简洁的描述。 :

An index only contains entities thathave every property referred to by theindex. If an entity does not have aproperty referred to by an index, theentity will not appear in the index,and will never be a result for thequery that uses the index.

Note thatthe App Engine datastore makes adistinction between an entity thatdoes not possess a property and anentity that possesses the propertywith a null value (None). If you wantevery entity of a kind to be apotential result for a query, you canuse a data model that assigns adefault value (such as None) toproperties used by query filters.

在您的情况下,您有 3 个实体根本没有设置 unit_pattern_set 属性(因为在创建这些实体时该属性未在模型中定义)- 因此这些属性在该实体的数据库表示中不存在,因此该实体不会出现在该实体的该属性的索引中。

丹·桑德森的书 Programming Google App Engine在 ~page 150 上对此进行了非常详细的解释(不幸的是,在 Google 图书预览中不可用)

要修复您已有的模型,您必须在 UnitPattern 上迭代查询(我没有测试以下代码,请在对实时数据运行之前检查它):

patterns = UnitPattern.all()
for pattern in patterns:
if not pattern.unit_pattern_set:
pattern.unit_pattern_set = None
pattern.put()

编辑:另外,Updating you model's schema文章讨论了您可以用来处理 future 此类架构更改的策略。然而,那篇文章已经很老了,它的方法需要一个网络浏览器不断点击一个 url 来触发下一个作业来更新更多的记录——现在 Task Queues存在,您可以使用一系列任务来进行更改。 article on using deferred.defer有一个您可以使用的框架 - 它会做少量工作,捕获 DeadlineExceededError,并使用处理程序将一个新任务排队,该任务从当前任务停止的地方开始。

关于google-app-engine - 如何在 Google 应用引擎数据库中过滤具有空引用的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2019717/

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