Reputation: 40664
Here is my class structure
class Mapping(ndb.Model):
id = ndb.StringProperty()
code = ndb.StringProperty()
class Doc(ndb.Model):
mappings = ndb.StructuredProperty('Mapping', repeated=True)
My code will scan a certain data set to create a series of mapping and add to an instance of Doc
. At the end, based on a certain criteria, I will decide to save the Doc
instance or not.
doc = Doc()
for data in dataset:
m = Mapping(parent=doc) # need to be able to reference the parent
m.put() # Did key get instantiated?
doc.mappings.append(m)
if good:
doc.put()
The problem is this:
When I try to iterate the list of mapping of doc.mapping
, I want to print out the key of the mapping instance.
print m.key.id()
But I will get this error message:
AttributeError: 'NoneType' object has no attribute 'id'
Why the 'key' is not instantiated after I called the put
method?
Upvotes: 1
Views: 92
Reputation: 12986
Models created to store in StructuredProperties do not have a key. These entities are serialized and stored in the property of the object. You can query on them if they have been indexed, but they do not exist as independent datastore entities, hence no Key. More information can be found in https://cloud.google.com/appengine/docs/python/ndb/properties#structured however you do have to read between the lines somewhat. Have a look at a stored entity in the Datastore viewer and you will also see there is no Key created for these properties.
Even though you put() the model they key component is not retained in mapping property.
In your case to achieve what you are attempting, you should be storing the keys of the Mapping as repeated KeyProperty and not as a StructuredProperty.
Looking deeper into the reason for this,you go hunting in the the code and look at the implementation of _retrieve_value
this uses _values
property of a Model to serialize the entity as a dict for storing in the StructuredProperty and the key
does not exist in _values
Upvotes: 1