views:

273

answers:

1

I have the following models:

class Author(db.Model):
    name = db.StringProperty()

class Story(db.Model):
    author = db.ReferenceProperty(Author)

What's the raw GQL to find all Stories by a certain author. In regular SQL, I will use joins but I don't think that's available in GQL.

Edit:

I'm looking for the raw GQL way, I know how to do it the Pythonic way. For instance something like(the following is probably totally wrong):

"SELECT * FROM Story WHERE author = :1", "Shakespeare"

I want to run the above from the GAE admin Data > Data Viewer > Query the Datastore. I want the raw SQL that someone could run from a typical mysql or psql shell.

+2  A: 

Edit2: Ah, the raw-GQL for use in the data-viewer...
Here's one way:

1) Run this and get the ID number:

SELECT * FROM Author where name = 'shakespeare'

2) Using ID number from previous query, run this:

SELECT * FROM Story where author = key('Author', 12345)

Edit: at long last, the raw GQL:
(Easiest way: Use the implicit backreference property name; in the form "modelname_set".)

qry = GqlQuery("SELECT * FROM Author WHERE name = :1", "shakespeare")
shakespeare = qry.get()
shakespeare.story_set # this property now contains all Shakespeare's stories

or

qry0 = GqlQuery("SELECT * FROM Author WHERE name = :1", "shakespeare")
shakespeare = qry0.get()

qry1 = GqlQuery("SELECT * FROM Story WHERE author = :1", shakespeare.key())
shakespeare_stories = qry1.fetch(10) # probably good to have some limit here

I prefer this way:

qry = Author.all()
qry.filter('name = ', 'shakespeare')
shakespeare = qry.get()

shakespeare.story_set # this property now contains all Shakespeare's stories

The more involved way may sometimes be necessary:

qry0 = Author.all()
qry0.filter('name = ', 'shakespeare')
shakespeare = qry0.get()

qry1 = Story.all()
qry1.filter('author = ', shakespeare.key())
shakespeare_stories = qry1.fetch(10) # probably good to have some limit here
Adam Bernier
I'm looking for the raw GQL way, I know how to do it the Pythonic way.
Thierry Lam
@Thierry: Indeed you are; please see the edited answer above.
Adam Bernier
I'm running the GQL from the Data Viewer, it gives you a window where you can run queries. I don't think I can run Python code from there.
Thierry Lam
You're right; no Python there :-( See edit2 above.
Adam Bernier