[英]Google NDB - required property inside StructuredProperty's structure not working as expected
I have encountered an issue with the required option from ndb.Model when it is placed inside a Model specified as a structure from a StructuredProperty. 将ndb.Model的必需选项放在指定为来自StructuredProperty的结构的模型中时,遇到了问题。
Here is the models definition : 这是模型的定义:
class SubModel(ndb.Model):
submodel_id = ndb.StringProperty(required=True)
class MyModel(ndb.Model):
model_id = ndb.StringProperty(required = True)
submodels = ndb.StructuredProperty(SubModel, repeated=True)
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
if 'submodels' in kwargs.keys():
_submodels = []
for kwarg in kwargs['submodels']:
if isinstance(kwarg, SubModel):
_submodels.append(kwarg)
else:
t = SubModel(**kwarg)
_submodels.append(t)
self.submodels = _submodels
What I want to do is either to create a model with no submodels or to create a model in which every submodels have a required id, otherwise, it raises an error. 我想要做的是要么创建一个没有子模型的模型,要么创建一个其中每个子模型都有一个必需ID的模型,否则会引发错误。
So when I test this model, I get these results : 因此,当我测试此模型时,我得到了以下结果:
args1 = {"model_id":"some_id","submodels":[{"submodel_id":null}]}
model1 = MyModel(**args1)
model1.put()
print model1.key.id()
# Everything works while submodel_id hasn't been set and it returns the key id from Google Datastore
args2 = {"model_id":null,"submodels":[{"submodel_id":"some_id"}]}
model2 = MyModel(**args2)
model2.put()
print model2.key.id()
# Google Datastore raises an error : Entity has uninitialized properties: model_id
Is this behavior standard behavior from ndb.StructuredProperty (meaning that no property options are considered from the structure specified) or should I implement what I want to do differently ? 这是ndb.StructuredProperty的行为标准行为(意味着从指定的结构中不考虑任何属性选项)还是应该以其他方式实现我想做的事情?
What I also want to do is to make Submodel inherit from ndb.Expando instead of ndb.Model but since ndb.Expando inherits from ndb.Model, that would be an even more precise question... 我还想做的是使Submodel从ndb.Expando继承而不是ndb.Model,但是由于ndb.Expando从ndb.Model继承,所以这将是一个更加精确的问题...
You have required = True
on 'model_id'. 您已在'model_id'上
required = True
。 You are trying to put()
an entity without defining one ( null
doesn't count). 您正在尝试将
put()
实体定义为一个实体( null
不计算在内)。
Your put()
s are on MyModel
. 您的
put()
位于MyModel
。 Not sure why the submodel_id
requirement in SubModel
isn't being checked when putting
on the parent model. 不知道为什么
submodel_id
在要求SubModel
时没有被检查putting
对父模型。 Seems it should be checked. 似乎应该检查它。 Can you check the datastore and see what has actually been
put()
? 您可以检查数据存储区并查看实际
put()
吗? When you read back that entity, what do you get? 当您读回该实体时,您会得到什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.