如何从结构化 属性 - python GAE 中删除实体?

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

我的模型结构如下所示:我正在为 google 应用引擎使用最新的 python SDK。

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()

我正在使用

获取 guido 模型的地址
addresses = Contact.query(Contact.name=="Guido").get().addresses
for address in addresses:
    if address.type == "work":
        # remove this address completely
        pass

我想从这个 guido 模型中删除 'work' 地址。这也应该在联系人和地址模型中删除。我该怎么做呢。在这种情况下,实体密钥会在 运行 时间内自动分配。

您需要做的是从列表中删除项目并保存。像这样:

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

我们在这里所做的是获取联系人,过滤其地址,然后将其保存回数据库。不需要进一步的工作。

关于删除Address实体的困惑,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.

这意味着您不需要单独删除它:) 看看您的数据存储查看器,应该只显示一个联系人实体,与您添加的地址数量无关。