Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an instance in an ndb repeated structured property

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
like image 263
voscausa Avatar asked Nov 30 '25 00:11

voscausa


1 Answers

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)
like image 154
Sologoub Avatar answered Dec 03 '25 00:12

Sologoub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!