How to get a list of key names in Python/Google app engine?
In Python/Google app engine, I'd like to store a property as a key name in order to save resources and speed things up. But I don't know how to get the list of key names.
As an example, consider the data model:
class Book(db.Model):
isbn = db.StringProperty() # Make this a key name instead.
category = db.StringProperty()
author = db.StringProperty()
title = db.StringProperty()
...
Now let's say I set the key name to the isbn instead of making it a property name:
new_book = Book(category="fantasy,comedy", title="The Light Fantastic", author="Terry Pratchett", key_name=isbn_number)
I guess that, if I could find a way of getting a list of key names, I would save resources? For example, when ch开发者_StackOverflow社区ecking if a particular book is already in the collection.
Is this correct, and how do I get a list of key names?
If this isn't the case, then would the following be a decent compromise:
class ISBN(db.Model):
isbn = db.StringProperty()
class Book(db.Model):
isbn = db.ReferenceProperty(ISBN)
category = db.StringProperty()
author = db.StringProperty()
title = db.StringProperty()
...
Would it save resources/be faster?
For the first approach, ISBN as key:
class Book(db.Model):
#isbn is key, so it shouldn't be a property
category = db.StringProperty()
author = db.StringProperty()
title = db.StringProperty()
new_book = Book(category="fantasy,comedy", title="The Light Fantastic", author="TerryPratchett", key_name=isbn_number)
Then getting list of all ISBNs:
isbns = [b.name() for Book.all(keys_only=True)]
Creating a Book
b = Book(key_name='isbn:0134815100494', **props)
b.put()
Querying
keys = Book.all(keys_only=True).fetch(100)
key_names = [key.name() for key in keys]
Look for keys_only
and key_name
when searching
You don't need a list of key names for your use case.
If you want to see if a book is already in the database, simply do Book.get_by_key_name(someISBN)
. There's also get_or_insert
for writes, which will check if the entity you're adding is already in the database, writing it if it's not and returning it if it is.
精彩评论