Vladimir
Vladimir

Reputation: 145

How to determine the child model of a polymodel entity on GAE?

That's how I query for contacts:

contacts = Contact.all()

Then, how to determine if a Contact is a Person or a Company with the following structure?

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()

Upvotes: 3

Views: 218

Answers (2)

aschmid00
aschmid00

Reputation: 7158

you can get the kind and class names in different ways

instance._class will return ['Contact', 'Person']

instance.class_name() returns Person

instance.kind() returns Contact

Upvotes: 1

Thanos Makris
Thanos Makris

Reputation: 3115

You can use the PolyModel class method class_name(). Quoting from the App Engine documentation:

PolyModel.class_name()

Returns the name of the class. A class can override this method if the name of the Python class changes, but entities should continue using the original class name.

In your code, if you insert two objects like the following:

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()

Then get all objects and print the class name by executing:

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

Output:

Class Name: Person

Class Name: Company

For information about the PolyModel class, take a look at The PolyModel Class

Upvotes: 1

Related Questions