Sengottuvel
Sengottuvel

Reputation: 37

How to remove an entity from structured property - python GAE?

I have model structure like the one below: I'm using latest python SDK for google app engine.

class Address(ndb.Model):
    type = ndb.StringProperty()  # E.g., 'home', 'work'
    street = ndb.StringProperty()
    city = ndb.StringProperty()
class Contact(ndb.Model):
    name = ndb.StringProperty()
    addresses = ndb.StructuredProperty(Address, repeated=True)
guido = Contact(
    name='Guido',
    addresses=[Address(type='home',city='Amsterdam'),
    Address(type='work', street='Spear St', city='SF')]
    )
guido.put()

I'm getting address for the guido model using

addresses = Contact.query(Contact.name=="Guido").get().addresses
for address in addresses:
    if address.type == "work":
        # remove this address completely
        pass

From this guido model I want to remove the 'work' address. This should also be deleted in Contact and Address model. How do I do this. In this case the entity keys are automatically assigned in the run time.

Upvotes: 1

Views: 746

Answers (1)

Jaime Gomez
Jaime Gomez

Reputation: 7067

What you need to do is remove the item from the list and save it. Something like this:

guido = Contact.query(Contact.name == 'Guido').get()
guido.addresses = [i for i in guido.addresses if i.type != 'work']
guido.put()

What we're doing here is getting the contact, filtering its addresses, then saving it back to the database. No further work is needed.

Regarding the confusion about deleting the Address entity, refer to the docs:

Although the Address instances are defined using the same syntax as for model classes, they are not full-fledged entities. They don't have their own keys in the Datastore. They cannot be retrieved independently of the Contact entity to which they belong.

This means you don't need to delete it separately :) take a look at your Datastore Viewer, only a Contact entity should show up, independently of how many addresses you have added.

Upvotes: 2

Related Questions