如何在 GAE ndb 中建模唯一约束

How to model a unique constraint in GAE ndb

我想要几个 "bundles" (Mjbundle),它们本质上是问题包 (Mjquestion)。 Mjquestion 有一个整数 "index" 属性 需要是唯一的,但它应该只在包含它的包内是唯一的。我不确定如何正确地建模这样的东西,我尝试使用下面的结构化(重复)属性 来做到这一点,但实际上还没有任何东西限制 Mjquestion 索引的唯一性。 better/normal/correct 这样做的方法是什么?

class Mjquestion(ndb.Model):
    """This is a Mjquestion."""
    index = ndb.IntegerProperty(indexed=True, required=True)
    genre1 = ndb.IntegerProperty(indexed=False, required=True, choices=[1,2,3,4,5,6,7])
    genre2 = ndb.IntegerProperty(indexed=False, required=True, choices=[1,2,3])
    #(will add a bunch of more data properties later)

class Mjbundle(ndb.Model):
    """This is a Mjbundle."""
    mjquestions = ndb.StructuredProperty(Mjquestion, repeated=True)
    time = ndb.DateTimeProperty(auto_now_add=True)

(使用上述模型并获取了某个 Mjbundle 实体,我不确定如何根据索引快速从 mjquestions 中获取 Mjquestion。关于过滤结构化属性的解释看起来适用于 Mjbundle 类型级别,而我已经有一个 Mjbundle 实体,并且不确定如何仅快速查询该实体包含的问题,而不是在代码中循环遍历它们 "manually"。)

所以我愿意接受任何关于如何做得更好的建议。

当您使用 StructuredProperty 时,所有类型的实体都存储为包含实体的一部分 - 因此当您获取包时,您已经获取了所有问题。如果您坚持这种存储方式,迭代检查代码就是解决方案。