coto
coto

Reputation: 2325

NDB query filter by KeyProperty

I have a class method in a ndb model, where I am filtering by 'user' (no problem with that) and by 'industry'.

The problem is that the entity Recommendation doesn't has industry property, but has stock property that is a KeyProperty of Stock, and Stock has a industry property

How can a fix the get_last_n_recommendations_for_user_and_industry method to filter by Industry, that is a KeyProperty of Stock??

class Industry(ndb.Model):
    name = ndb.StringProperty()
    ...

class Stock(ndb.Model):
    name = ndb.StringProperty()
    industry = ndb.KeyProperty(kind=Industry)
    ...

    @classmethod
    def get_industry(cls):
        return cls.query(cls.ticker == cls).get().industry

class Recommendation(ndb.Model):
    user = ndb.KeyProperty(kind=User)
    stock = ndb.KeyProperty(kind=Stock)
    ...

    @classmethod
    def get_last_n_recommendations_for_user_and_industry(cls, stock_key, user_key, n):
        return cls.query(
                cls.user == user_key, 
                cls.stock.get().industry == ndb.Key('Stock', stock_key.string_id()).get().industry
            )
            .fetch(page_size)

When I do this, I have this error:

AttributeError: 'KeyProperty' object has no attribute 'get'

Upvotes: 1

Views: 3630

Answers (1)

Shay Erlichmen
Shay Erlichmen

Reputation: 31928

You can't filter/query by an attribute of a reference property, you will need to add a attribute of industry to the Recommendation model and query on it.

class Recommendation(ndb.Model):
  user = ndb.KeyProperty(kind=User)
  stock = ndb.KeyProperty(kind=Stock)
  industry = ndb.ComputedProperty(lambda e:  
    Stock.industry.get_value_for_datastore(e.stock))

  @classmethod
  def get_last_n_recommendations_for_user_and_industry(cls, industry_key, user_key, n):
    return cls.query(
            cls.user == user_key, 
            cls.industry == ndb.Key('Stock', stock_key.string_id()).get().industry
        )
        .fetch(page_size)

Upvotes: 6

Related Questions