如何将实体的父级设置为属性?
我想做这样的事情:
e = Employee(key_name = 'john',name='john the first')
e.put()
a = Address(key_name='addr_john',street='66th street')
a.parent = e;
a.put();
addr = Address.gql("WHERE ANCESTOR IS :1", e).fetch(1) #len(addr)==0
但它不起作用,如果我在构造函数中设置父级,它就会起作用。
a = Address(key_name='addr_john',street='66th street',parent=e)
但我不想这样做,我需要在创建对象后这样做。
i want to do something like this:
e = Employee(key_name = 'john',name='john the first')
e.put()
a = Address(key_name='addr_john',street='66th street')
a.parent = e;
a.put();
addr = Address.gql("WHERE ANCESTOR IS :1", e).fetch(1) #len(addr)==0
But it doesn't works, it just works if i set the parent in the constructor.
a = Address(key_name='addr_john',street='66th street',parent=e)
But i don't want to do it, i need to do it after i create the object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实体的父级只能在其创建期间设置,因此只能在 db.Model 子类实例的构造函数中设置。尝试分配给
db.Model
实例的parent
属性将导致其parent()
函数被覆盖,但相应数据存储的实际父级实体不会改变。如果在创建子对象期间无法建立关系,则应考虑将其编码为普通属性。
或者(如果由于您需要的事务而无法承担没有父子关系的后果)您可以尝试推迟子对象的创建,直到您可以确定它应该具有哪个父对象。由于显然您还使用父数据(即
Employee
的name
)为子实体建立key_name
,因此这种方法似乎是有意义的。 (键名,如父项,也只能在实体创建期间设置)。Parent for an entity can only be set during its creation, so only in a constructor of
db.Model
subclass instance. Attempting to assign toparent
attribute ofdb.Model
instance would result in itsparent()
function being overwritten, but the actual parent for corresponding datastore entity will not be changed.If you have relationship that cannot be established during creation of child object, you should consider coding it as ordinary property.
Alternatively (if you cannot afford not having the parent-child relation due to transactions you need) you could try to defer creation of child object until you can determine which parent it should have. Since apparently you also use the parent data (i.e.
name
ofEmployee
) to establish akey_name
for child entity, this approach seems to make sense. (Key names, like parents, can also be set only during entity's creation).