0

我在ndb模型中有一個類方法,我通過'user'(沒有問題)和'industry'進行過濾。通過KeyProperty的NDB查詢過濾器

的問題是,實體建議不具有行業財產,但股票屬性,它是股票的KeyProperty和股票行業財產

如何可以修復get_last_n_recommendations_for_user_and_industry方法按行業過濾,這是股票的關鍵屬性??

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) 

當我這樣做,我有這樣的錯誤:

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

回答

5

您不能過濾/查詢通過參考屬性的屬性,則需要行業的屬性添加到建議模型和查詢。

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)