1

我在 ndb 模型中有一个类方法,我在其中按“用户”(没问题)和“行业”进行过滤。

问题是实体Recommendation没有行业属性,但具有Stock属性,即 Stock 的 KeyProperty,而Stock具有行业属性

如何修复get_last_n_recommendations_for_user_and_industry方法以按行业过滤,即股票的 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'
4

1 回答 1

6

您不能通过引用属性的属性过滤/查询,您需要将行业属性添加到推荐模型并对其进行查询。

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)
于 2012-07-23T06:47:29.723 回答