Reputation: 11706
When I have a NDB repeated property, i have to iterate over the list to find the property I am looking for. When I look in the datastore, every property of the structured property is a list. I thought I could use the Python list index method, but this does not work.
So is there an easy way to find the structured property instance I need.
class Instance(ndb.Model)
instance_id = ndb.StringProperty()
instance_data = ndb.TextProperty()
class Example(ndb.Model):
instances = ndb.StructuredProperty(Instance, repeated = True)
I tried:
instance_id = 'thisone'
index = entity.instances.instance_id.index(instance_id)
data = entity.instances.instance_data[index]
But I had to :
instance_id = 'thisone'
for each in entity.instances :
if each.instance_id = instance_id :
instance_data = each.instance_data
break
Upvotes: 3
Views: 2129
Reputation: 5352
So here's the problem - entity.instances is a python list, as per documentation here. What you are trying to do is more like a dict. There is a feature request that Guido turned down in the Google Group that seems to be the same thing as what you are asking: https://groups.google.com/d/topic/appengine-ndb-discuss/Kj7Ymhr5hlE/discussion
The entity.instances[0] returns the first instance in that list. All other List operations seem to work as well. But you are trying to effectively query that list.
If you already know what the ID is and your lists are large, you could always set that ID as the key and make a call to the datastore to get just that instance. When you create the instance do something like this:
new_instance = Instance(id=instance_id, instance_data=some_data)
and then load it like this:
existing_instance = Instance.get_by_id(instance_id)
Upvotes: 2