gpt4 book ai didi

python - StructuredProperty 的重复嵌套属性

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

虽然 NDB 文档说:

Although a StructuredProperty can be repeated and a StructuredProperty can contain another StructuredProperty, beware: if one structured property contains another, only one of them can be repeated.

在我看来,文档最清晰的解释可以正确地写为“如果一个结构化属性包含另一个结构化属性”。

在这种情况下,我希望这样的事情能够起作用:

class KeyList(ndb.Model):
keys = ndb.KeyProperty(repeated=True)

class Collection(ndb.Model):
lists = ndb.StructuredProperty(KeyList, repeated=True)

但是,此操作失败并出现错误:

TypeError: This StructuredProperty cannot use repeated=True because its model class (KeyList) contains repeated properties (directly or indirectly).

似乎无法在重复的 StructuredProperty 中嵌套任何重复属性。

从代码来看,这个looks to be the intended behaviour .

在这种情况下,开发应用程序服务器可能与记录的行为不同。如果我读到的文档是正确的,那么修复 the condition in the development server giving rise to the above error可能是这样的:

if modelclass._has_repeated and isinstance(modelclass, StructuredProperty):
# ...

AppEngine StructuredProperty 是否应该能够包含重复属性(重复的 StructuredProperty 除外)?

问题报告在这里:https://github.com/GoogleCloudPlatform/appengine-python-vm-runtime/issues/40

编辑值得注意的是 golang docs说这个:

Slices of structs are valid, as are structs that contain slices. However, if one struct contains another, then at most one of those can be repeated. This disqualifies recursively defined struct types: any struct T that (directly or indirectly) contains a []T.

我从中得到的含义是,重复结构上的重复非结构属性在 BigTable 级别并不是本质上被禁止的,而是 Python 实现的副作用。

如果没有进一步的证实,我不会依赖这个暗示。

最佳答案

这是我们文档中的一个错误 --

使用StructuredProperty,您只能拥有单层重复属性。

<小时/>

一些背景:

ndb 通过在写入数据存储区之前分解属性来处理 StructuredProperty。例如:

class Inner(ndb.Model):
a = ndb.StringProperty()

class Outer(ndb.Model):
inner = ndb.StructuredProperty(Inner, repeated=True)

然后,如果我们编写:Outer(inner=[Inner(a="1"), Inner(a="2")]),这实际上会写入数据存储区:

{
inner.a = ["1", "2"]
}

但是,如果重复Inner.a,我们可以编写如下内容:

 Outer(inner=[Inner(a=["1", "3"]), Inner(a=["2", "4"])])

这将被写入数据存储,如下所示:

{
inner.a : ["1", "3", "2", "4"]
}

然后当我们读到这个时,我们不知道如何解析,因为所有这些都是有效的:

Outer(inner=[Inner(a=["1", "3"]), Inner(a=["2", "4"])])
Outer(inner=[Inner(a=["1", "3", "2"]), Inner(a=["4"])])
Outer(inner=[Inner(a=["1"]), Inner(a=["3"]), Inner(a=["2"]), Inner(a=["4"])])
Outer(inner=[Inner(a=[]), Inner(a=["1", "3", "2", "4"])])

请注意,其他库(例如 Objectify)可以通过存储用于索引的分解属性和整个数据集的未索引 blob(可以维护反序列化结构)来避免此问题。

关于python - StructuredProperty 的重复嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34790724/

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