Jeff C.
Jeff C.

Reputation: 97

Gql Query on ReferenceProperty()

Short version of my question: What is the Gql syntax for a query filtering based on a reference property?

Long version of my question: Assume the following model:

Class User(db.Model):
    username = db.StringProperty()
    password = db.StringProperty()

Class Portfolios(db.Model):
    portname = db.StringProperty()

Class Portfolio_Owners(db.Model):
    port_id = db.ReferenceProperty(Portfolios)
    user_id = db.ReferenceProperty(User)
    key_string = db.StringProperty()

I want to query Portfolio_Owners based on user_id (which is a ReferenceProperty).

However, i can not query on a string of the .user_id property as you would on a StringProperty (the following returns an empty list):

key_string = 'aglwb3J0Zm9saW9yCwsSBFVzZXIY6gEM'

que=db.GqlQuery("SELECT * FROM Portfolio_Owners WHERE user_id=:1", key_string)

entity = que.fetch(limit=10)

Nor can i query on a key object of that user (the following also returns an empty list):

key_object = db.Key('aglwb3J0Zm9saW9yCwsSBFVzZXIY6gEM')

que=db.GqlQuery("SELECT * FROM Portfolio_Owners WHERE __key__=:1", key_object)

entity = que.fetch(limit=10)

And yes, I certain the user_id is correct...here is the copy-paste from the Datastore Viewer:

Entity Kind  Portfolio_Owners
Entity Key   aglwb3J0Zm9saW9yFwsSEFBvcnRmb2xpb19Pd25lcnMYhQIM
ID   261
user_id (Key)   aglwb3J0Zm9saW9yCwsSBFVzZXIY6gEM
User:           id=234

port_id (Key)   aglwb3J0Zm9saW9yEQsSClBvcnRmb2xpb3MYhAIM
Portfolios:     id=260 

I have not found the answer in App Engine docs, App Engine msg boards, or elsewhere on SO.

thanks!

Upvotes: 0

Views: 1430

Answers (1)

Drew Sears
Drew Sears

Reputation: 12838

So aglwb3J0Zm9saW9yCwsSBFVzZXIY6gEM is your user key, right? Let's start with this:

user = db.Key('aglwb3J0Zm9saW9yCwsSBFVzZXIY6gEM')
que = db.GqlQuery("SELECT * FROM Portfolio_Owners WHERE user_id = :1", user)

This should give you any Portfolio_Owners entities that refer to this user.

You can shorten that to this:

user = db.get('aglwb3J0Zm9saW9yCwsSBFVzZXIY6gEM')
que = user.Portfolio_Owners_set

The datastore is fundamentally very different from SQL. Based on your code samples, I think you would benefit from revisiting the docs to get a better understanding of datastore design:

http://code.google.com/appengine/docs/python/datastore/entities.html

Upvotes: 1

Related Questions