Skip to main content
 首页 » 编程设计

python之NDB 查询重复 StringProperty 中的空字符串

2024年10月24日28xiaohuochai

我有一个具有 String 重复属性的 ndb 模态。我正在尝试检索所有具有空值的实体。但是 NDB 查询返回空。

class A(ndb.model): 
    name = ndb.StringProperty() 
    values = ndb.StringProperty(repeated=True) 
 
a1 = A() 
a1.name = "T1" 
a1.values = ['V1', 'V2'] 
a1.put() 
 
a2 = A() 
a2.name = "T2" 
a2.values = [] 
a2.put() 
 
result = A.query(A.values=="") # Return empty 
result = A.query(A.values==[]) # BadValueError: Expected string, got [] 
 
for each in result: 
  print each.name 

如何查询具有空值/无值的实体?

请您参考如下方法:

我认为您必须将查询基于另一个包含值数量的字段,例如,

num_values = ndb.IntegerProperty(indexed=True) 

每次更新 value 字段时,您都必须更新此数字。然后你可以这样查询:

result = A.query(A.num_values==0) 

这类似于另一个问题:NDB: Sort query results