How to set the parent of an entity as a property?
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();
add开发者_如何学运维r = 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.
Parent for an entity can only be set during its creation, so only in a constructor of db.Model
subclass instance. Attempting to assign to parent
attribute of db.Model
instance would result in its parent()
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
of Employee
) to establish a key_name
for child entity, this approach seems to make sense. (Key names, like parents, can also be set only during entity's creation).
精彩评论