db.Model is the general class representing a database table. To create a specific table, we define a subclass of db.Model, e.g., class Product (db.model): name = db.StringProperty() price = db.FloatProperty() # ... All Model classes have a function key() and a property key which return the unique identifier that is assigned to any instance (record) of the class. If I have a specific product, for instance, I can get to the key with: key = product.key() # or product.key Given a key, I can get the corresponding object in two ways. For instance, if I had the key of a particular product, I could get the object with:product= db.get(key) # or product= Product.get(key) Often, you can avoid dealing directly with keys by using higher-level functionality such as the ReferenceProperty. Consider the following class, which maps individuals to groups: class PersonGroup: Beneath the hood, the database table uses the keys of each Person and Group for the mapping. But the application programmer deals with objects-- you get to bypass using the key to get an object.person = db.ReferenceProperty(Person) group = db.ReferenceProperty(Group) Using the Key to Identify an Object One situation where you would use the a key explicitly is to uniquely identify a choice by the end-user. Consider the following form: <form action="/on_to_group" method="post"> {% for person in people %} <b>{{person.first}} {{person.last}}</b> <input type="checkbox" name="person_check" value={{person.key}}> <input type="hidden" name="group_name" value={{group.name}}> {% endfor %} <input type="submit" value="add to group"> </form> Here, we have a form which allows the user to check the person he wants to add to a group. On submit, we need to convey the person and group to the controller. For the person, we send the key back as the value of the checkbox. For the group, the HTML hidden field input type is used-- we don't want the group name to appear as part of the form, but it does need to be sent. The controller handling the on_to_group action can get the chosen person using the key: key= self.request.get('person_check') person = Person.get(key) In-Class worksheet With pencil and paper, sketch out the HTML code for displaying a list of persons (first and last) and making each person in the list linkable. Assume that the controller has sent 'people' a list of persons, for you to work with. |