继承基于ndb.Model的类,Python

时间:2015-09-11 22:30:22

标签: python

我目前有一个使用以下代码的项目:

Classes.py

class Session(Conference, ndb.Model):
    ''' Session - A Session object '''
    # The session's name
    sessionName     = ndb.StringProperty()
    # Highlights of the session
    highlights      = ndb.StringProperty(repeated = True)
    # The session's speaker
    speaker         = ndb.StringProperty()
    # How long the session will last
    duration        = ndb.TimeProperty()
    # The type of session (Workshop, lecture, etc...); Default 'Not Specified'
    typeOfSession   = ndb.StringProperty(default = 'NOT_SPECIFIED')
    # Date the session takes place on
    date            = ndb.DateProperty()
    # The time the session starts
    startTime       = ndb.TimeProperty()
    # The Conference this Session is at
    parentConf      = Conference

class Conference(ndb.Model):
    '''Conference -- Conference object'''
    name            = ndb.StringProperty(required=True)
    description     = ndb.StringProperty()
    organizerUserId = ndb.StringProperty()
    topics          = ndb.StringProperty(repeated=True)
    city            = ndb.StringProperty()
    startDate       = ndb.DateProperty()
    month           = ndb.IntegerProperty() # TODO: do we need for indexing like Java?
    endDate         = ndb.DateProperty()
    maxAttendees    = ndb.IntegerProperty()
    seatsAvailable  = ndb.IntegerProperty()

我正在尝试调用代码     conf =会议(**数据).put()     variable = Session(conf,** data).put()

其中conf是会议对象(我已经验证了这一点) **数据是一个输入数据数组,有效(我已对此进行了测试) 但是当我调用此函数时,我收到错误

' TypeError:模型构造函数不带位置参数。'

经过一些搜索,我发现是由于我试图重载ndb.Model的构造函数,我已经告知我不应该这样做。

所以我的问题是,我如何管理这种继承,其中Session是Conference的孩子,但在构建期间仍然需要ndb.Model数据?谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

使用PolyModel进行数据存储继承 - > https://developers.google.com/appengine/docs/python/ndb/polymodelclass

以下是一个例子:

from google.appengine.ext import ndb
from google.appengine.ext.ndb import polymodel

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

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

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

p = Person(phone_number='1-206-555-9234',
           address='123 First Ave., Seattle, WA, 98101',
           first_name='Alfred',
           last_name='Smith',
           mobile_number='1-206-555-0117')
p.put()

c = Company(phone_number='1-503-555-9123',
            address='P.O. Box 98765, Salem, OR, 97301',
            name='Data Solutions, LLC',
            fax_number='1-503-555-6622')
c.put()

for contact in Contact.query():
  print 'Phone: %s\nAddress: %s\n\n' % (contact.phone_number, contact.address)