Cu7l4ss
Cu7l4ss

Reputation: 566

Gql get all children of ancestor without the ancestor itself

I'm trying to build a forum like platform on GAE.

I must mention first: I'm a bit new to GAE.

I want to pull all replies to a specific post. So far the structure looks like so:

- Forum
--- Post
----- Reply ( = Post with Post as a parent )

Replies are just posts with post as their parent(instead of the forum as a parent).

The problem begins when I try to pull out all of the replies, the returned results include the ancestor itself.

How can I achieve the same without the ancestor itself?(Might need to mention also that I searched for a solution but haven't found one)

Edit:

My query is like so:

replies = db.GqlQuery("SELECT * FROM Post WHERE ANCESTOR IS :1", post)

Thanks!

Update:

Well I've found a way:

db.GqlQuery("SELECT * FROM Post WHERE ANCESTOR IS :1 AND __key__ != :2", post, post.key())

just query and rule out the ancestor itself in the where clause!

Upvotes: 1

Views: 2626

Answers (3)

Nick Johnson
Nick Johnson

Reputation: 101139

Your proposed solution uses an inequality filter in the query. Inequality filters aren't supported by the underlying datastore, and are internally translated into two separate queries, like so:

SELECT * FROM Post WHERE ANCESTOR IS :1 AND __key__ < :2
SELECT * FROM Post WHERE ANCESTOR IS :1 AND __key__ > :2

Obviously, this is substantially less efficient. A much simpler and more efficient option is to simply fetch all results, then discard the one entity that you don't want.

Upvotes: 2

Robert Kluin
Robert Kluin

Reputation: 8292

If you have the parent key you do not have to fetch the parent post entity. If you have a string version of the parent post's key:

parent_post = db.Key(string_version_of_the_key)
replies = Post.all().ancestor(parent_post).fetch(num_to_fetch)

If you have the parent post's key id or name:

parent_post = db.Key.from_path('Post', id_or_key_name)
replies = Post.all().ancestor(parent_post).fetch(num_to_fetch)

See the docs on the Key class for more details.

Upvotes: 2

Adam Crossland
Adam Crossland

Reputation: 14213

I don't know if your code is in Python or not, but your query should look something like this:

replies = Reply.ancestor(post).fetch(num_to_fetch)

that will definitely not return post in your result set, as an entity can not be its own ancestor.

Upvotes: 1

Related Questions