google cloud datastore - gae ndb query failing to find related records with key property -
i'm trying implement code won't let entity deleted if has related entities.
class father(ndb.model): name = ndb.stringproperty(indexed=true) class son(ndb.model): name = ndb.stringproperty(indexed=true) father = ndb.keyproperty(father)
this code:
father = father.get_by_id(long(keynumber)) if father: father_key = father.key if father_key: sons = son.query(son.father==father_key).fetch() number_of_sons = len(sons) if number_of_sons == 0: father_key.delete()
when runs, sons empty list [] although there related sons father.
why doesn't query work?
as @patrick costello suggests, using strongly-consistent query right way handle this:
class father(ndb.model): name = ndb.stringproperty(indexed=true) class son(ndb.model): name = ndb.stringproperty(indexed=true) @classmethod def create(cls, name, father): son = cls(name=name, parent=father) son.put()
i recommend using count()
operation:
father = father.get_by_id(long(keynumber)) if father: father_key = father.key if father_key: sons_exist = son.query(ancestor=father_key).count(1) if sons_exist == 0: father_key.delete()
by counting 1, result of count(1)
true/false (1/0) value.
not exact duplicate, this question similar.
Comments
Post a Comment