【问题标题】:NDB query filter by KeyProperty按 KeyProperty 的 NDB 查询过滤器
【发布时间】:2012-07-23 06:02:50
【问题描述】:

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

问题是实体 Recommendation 不具有 industry 属性,但具有 stock 属性,即 Stock 的 KeyProperty,并且股票具有行业属性

如何修复 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'

【问题讨论】:

    标签: python google-app-engine google-cloud-datastore app-engine-ndb


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 2015-04-14
      • 1970-01-01
      相关资源
      最近更新 更多