ndb.StructuredProperty没有调用ndb.PolyModel子类方法

时间:2013-11-09 00:20:52

标签: python google-app-engine polymodel

将ndb.Polymodel超类存储为ndb.StructuredProperty时,我无法访问子类方法;改为调用超类方法并引发NotImplementedError。这是我想要完成的一个简略版本。

class Recipient(polymodel.PolyModel):
  name = ndb.StringProperty()

  def PrettyPrinting(self):
    raise NotImplementedError, 'Rawr'


class ShippingRecipient(Recipient):
  address_line_one = ndb.StringProperty()
  #there are other properties, but they aren't necessary here.

  def PrettyPrinting(self):
    return 'Hey, this should be called.'


class LocalRecipient(Recipient):
  distribution_location = ndb.StringProperty()
  #same deal, more attributes, but useless for this example.

  def PrettyPrinting(self):
    return 'Hey this should be called.'

class Shipment(ndb.Model):
  recipient = ndb.StructuredProperty(Recipient)

现在说我已保存货件并将ShippingRecipient存储到货件的收件人字段中。在数据存储区中,货件recipient.class == ['收件人','ShippingRecipient']。我打电话的时候:

shipment = Shipment.get_by_id('some_key')
shipment.recipient.PrettyPrinting()

引发NotImplementedError而不是PrettyPrinting(...)的ShippingRecipient实现。我希望在访问货件的收件人字段时调用子类方法。有没有办法可以改为使用子类方法?我知道说结构化属性是Recipient类型会导致调用超类方法,但是我可能还不完全理解为什么它们会将子类存储在recipient.class属性中。

1 个答案:

答案 0 :(得分:1)

我不相信这可行。它只会存储收件人实例 如果你看一下PolyModel是如何工作的,所有变体都存储为基类, 在您的示例Recipient中。它还存储子类名称,当从数据存储中检索它时,它会重新创建特定的子类。

我真的怀疑他们是否会将此机制构建到StructuredProperty实例化中,并且您已经发现了这种情况。

相关问题