我在ndb模型中有一个类方法,我按“用户”(没有问题)和“行业”过滤。
问题是实体推荐没有行业属性,但有 stock 属性是Stock的KeyProperty,并且股票有行业属性
如何修复 get_last_n_recommendations_for_user_and_industry 方法按行业过滤,即Stock的KeyProperty?
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'
答案 0 :(得分:5)
您无法通过引用属性的属性进行过滤/查询,您需要在Recommendation模型中添加行业属性并对其进行查询。
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)