Query to database with 'primary key' on GoogleAppEngine?

164 Views Asked by At

I've made a guestbook application using Google App Engine(GAE):python and the client is running on iPhone.

It has ability to write messages on the board with nickname.
The entity has 3 fileds:

  1. nickname
  2. date
  3. message

And I'm about to make another feature that user can post reply(or comment) on a message.

But to do this, I think there should a 'primary key' to the guestbook entity, so I can put some information about the reply on a message.

With that three fields, I can't get just one message out of database.

I'm a newbie to database. Does database save some kind of index automatically? or is it has to be done by user?

And if it's done automatically by database itself(or not), how can I get just one entity with the key??

And I want to get some advise about how to make reply feature generally also. Thanks to read.

2

There are 2 best solutions below

1
On BEST ANSWER

Every entity has a key. If you don't assign a key_name when you create the entity, part of the key is an automatically-assigned numeric ID. Properties other than long text fields are automatically indexed unless you specify otherwise.

To get an entity if you know the key, you simply do db.get(key). For the replies, you probably want to use a db.ReferenceProperty in the reply entity to point to the parent message; this will automatically create a backreference query in the message to get replies.

1
On

Each entity has a key, it contains information such as the kind of entity it is, it's namespace, parent entities, and the most importantly a unique identifier (optionally user specifiable).

You can get the key of an entity using the key method that all entities have.

message.key()

A key can be converted to and from a URL-safe string.

message_key = str(message.key())
message = Message.get(message_key)

If the key has a user-specified unique identifier (key name), you can access it like this

message.key().name()

Alternatively, if a key name was not specified, an id will be automatically assigned.

message.key().id()

To assign a key name to an entity, you must specify it when creating the entity, you are not able to add/remove or change the key name afterwards.

message = Message(key_name='someusefulstring', content='etc')
message.put()

You will then be able to fetch the message from the datastore using the key name

message = Message.get_by_key_name('someusefulstring')

Use the db.ReferenceProperty to store a reference to another entity (can be of any kind)

It's a good idea to use key name whenever possible, as fetching from the datastore is much faster using them, as it doesn't involve querying.