Reputation: 2050
In the GAE I'm trying to find a way to implement or construct something similar to a foreign key constraint in a SQL database. Basically, deleting an entity that is being refered by another entity via a foreign key constraint should not be allowed (in other words: deleting a parent should not be allowed if there are children that refer to that parent).
I tried the KeyProperty
in the ndb datastore but that gives me no options to find all depenend entites from the entity I want to delete. Also the ancestor
hierarchy doesn't seem to cut it. I can query the ancestor
from the children, but there doesn't seem a way to query the children from the ancestor
.
Is there any way to either get the children from an ancestor
or another database design in the GAE ndb datastore to implement this foreign key constraint?
Upvotes: 1
Views: 409
Reputation: 12986
Is there any way to either get the children from an ancestor
Yes it's called a query, used in conjunction with a KeyProperty in the child holding the key of the parent, or having the parent as the ancestor of the child key.
You can find all children of an ancestor irrespective of kind using an kindless ancestor query - https://cloud.google.com/appengine/docs/python/datastore/queries?hl=en#Python_Kindless_ancestor_queries
There is no such thing as a foreign key constraint in the datastore.
Not sure how it doesn't "cut it" apart from not performing the delete for you.
Upvotes: 1
Reputation: 600059
As Tim points out, if you use the ancestor solution you can easily query for all children. The same would be true if you use KeyProperty; you can easily query for all entities pointing at the current key:
MyChildModel.all().filter(MyChildModel.my_key_property==my_parent_entity.key)
Again, it's not clear how this fairly simple solution wouldn't "cut it".
However it is worth mentioning that it is a fundamental mistake to treat the datastore as if it were a relational database. It is not, and you should not try. You cannot enforce referential integrity; eventual consistency makes that impossible.
Upvotes: 0