Eduardo
Eduardo

Reputation: 1413

Querying nested KeyProperties

I have the following models:

class Company(ndb.Model):
    name = ndb.StringProperty(indexed=False)
    # some other fields

class User(polymodel.PolyModel):
    company = ndb.KeyProperty(kind=Company)
    # some other fields

class Object(ndb.Model):
    user = ndb.KeyProperty(kind=User)
    # some other fields

Now I have a user and I want to query Objects that are associated with other Users in the same company like this:

Object.query(Object.user.company == user.company)

Of course, this doesn't work, since Object.user is a key and I cannot access anything beyond that.

Is there any way to do it? I only need the company key, I was thinking on a ComputedProperty but I'm not sure if it's the best solution. Also, it would be better to query based on any field in company.

Upvotes: 0

Views: 50

Answers (1)

Tim Hoffman
Tim Hoffman

Reputation: 12986

You need to denormalize and store redundant information, as the datastore doesn't support joins.

For instance given your models above, a user can only be a member of one company, if you really need to search all objects whose user is a member of a particular company then store the company key in the Object.

Use a computed property if that works best for you.

Alternately use a factory that always takes the User as a argument and construct Object that way.

Upvotes: 1

Related Questions