【问题标题】:How to determine the child model of a polymodel entity on GAE?如何确定 GAE 上多模型实体的子模型?
【发布时间】:2012-10-30 14:28:11
【问题描述】:

这就是我查询联系人的方式:

contacts = Contact.all()

那么,如何判断Contact是Person还是Company,结构如下?

class Contact(polymodel.PolyModel):
    phone_number = db.PhoneNumberProperty()
    address = db.PostalAddressProperty()

class Person(Contact):
    first_name = db.StringProperty()
    last_name = db.StringProperty()
    mobile_number = db.PhoneNumberProperty()

class Company(Contact):
    name = db.StringProperty()
    fax_number = db.PhoneNumberProperty()

【问题讨论】:

  • 看起来 class_name() 方法现在已弃用

标签: python google-app-engine google-cloud-datastore data-modeling


【解决方案1】:

你可以通过不同的方式获取种类和类名

instance._class 将返回['Contact', 'Person']

instance.class_name() 返回Person

instance.kind() 返回Contact

【讨论】:

    【解决方案2】:

    您可以使用PolyModel 类方法class_name()。引用 App Engine 文档:

    PolyModel.class_name()

    返回类的名称。如果 Python 类的名称发生更改,类可以覆盖此方法,但实体应继续使用原始类名。

    在您的代码中,如果您插入两个对象,如下所示:

    p = Person(first_name='John',
               last_name='Doe',
               mobile_number='1-111-111-1111')
    p.put()
            
    c = Company(name='My company',
                fax_number='1-222-222-2222')
    c.put()
    

    然后通过执行获取所有对象并打印类名:

    for c in Contact.all():
        logging.info('Class Name: ' + c.class_name())
    

    输出:

    类名:人

    班级名称:公司

    有关 PolyModel 类的信息,请查看The PolyModel Class

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      相关资源
      最近更新 更多