简体   繁体   中英

Need help setting up ndb.StructuredProperty for One-to-Many Relationship

I am creating an application using Python (2.7) and GAE. I am trying to create a one-to-many relationship. There is one client with numerous properties which also has many potential contacts. Contacts also has various properties. The example of using the ndb.StructuredProperty seems pretty straight forward, but when I import my data model with a structured property line, I keep getting the following error in my log:

NameError: Name 'Contact' is not defined.

Any help would be greatly appreciated.

main.py

from dataObjects import *

dataObjects.py

class Client(ndb.Model):
    createDate = ndb.DateProperty()
    name = ndb.StringProperty()
    address1 = ndb.StringProperty()
    address2 = ndb.StringProperty()
    state = ndb.StringProperty()
    zipCode = ndb.StringProperty()
    phone = ndb.StringProperty()
    fax = ndb.StringProperty()
    website = ndb.StringProperty()
    city = ndb.StringProperty()
    industry = ndb.StringProperty()
    status = ndb.StringProperty()
    notes = ndb.StringProperty()
    financing = ndb.StringProperty()
    contacts = ndb.StructuredProperty(Contact, repeated=True)

class Contact(ndb.Model):
    firstName = ndb.StringProperty()
    lastName = ndb.StringProperty()
    role = ndb.StringProperty()
    status = ndb.StringProperty()
    phone = ndb.StringProperty()
    fax = ndb.StringProperty()
    email = ndb.StringProperty()
    createDate = ndb.DateProperty()
    isClient = ndb.StringProperty()
    address = ndb.StringProperty()

As Daniel Roseman pointed out :

"Because it's not defined yet. Swap the order of the models."

Basically, when creating the model Client, your code needs a Contact object. Since Contact doesn't exist for your code, it breaks.

Also, for cases when its not possible to just change the order of definition you can add a property after the model were defined (that includes self-referencing):

class User(ndb.Model):
  pass

User.friends = ndb.StructuredProperty(User, repeated=True)
User._fix_up_properties()

您必须交换2个模型的顺序,就像定义客户端模型时未定义Contact模型一样。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM