NDB: 查询未设置的属性?

8 投票
1 回答
3189 浏览
提问于 2025-04-18 12:32

我在生产环境中收集了一些数据,假设我们有一个这样的模型:

class Tags(ndb.Model):
    dt_added = ndb.DateTimeProperty(auto_now_add=True)
    s_name   = ndb.StringProperty(required=True, indexed=True)

现在我想给这个模型添加一个新属性:

class Foo(ndb.Model):
    is_valid = ndb.BooleanProperty(default=False)
    some_key = ndb.KeyProperty(repeated=True)

class Tags(ndb.Model):
    dt_added = ndb.DateTimeProperty(auto_now_add=True)
    name     = ndb.StringProperty(required=True, indexed=True)
    new_prop = ndb.StructuredProperty(Foo)

... 然后用这个新模型再收集一些数据。

所以现在我有一部分数据是有这个新属性 new_prop 的,而另一部分数据则没有这个属性。

我的问题是:我该如何查询那些没有设置新属性 new_prop 的数据呢?

我试过:

query_tags = Tags.query(Tags.new_prop == None).fetch()

但是似乎没有找到没有这个属性的数据... 有什么建议吗?谢谢!

1 个回答

6

在数据存储中,有两种情况:一种是实体没有某个属性,另一种是实体有这个属性,但它的值是空的(也就是None)。

你不能直接查询那些缺少某个特定属性的实体。一个可行的办法是先定义一个固定的属性,并把它的默认值设为None,然后再筛选出那些这个属性值为None的实体。

撰写回答