Google App Engine NDB中如何通过ComputedProperty获取键名长度
Hey there! Let's work through this problem together. The issue with your current code is that e.get_by_id is a class method for fetching entities, not a way to access the current entity's own key. To get the key of the entity you're working with, you need to use e.key instead.
Correct Approaches
1. Simple Lambda (For String-Only Keys)
If you only use string names for your keys (no numeric IDs), you can simplify this to a clean lambda:
key_name_length = ndb.ComputedProperty(lambda e: len(e.key.id()))
Here, e.key grabs the entity's Key object, and e.key.id() returns the string name of the key (since you mentioned you're working with letter collections like xyz).
2. Safe Lambda (Handles Numeric IDs Too)
If some of your keys might use numeric IDs instead of string names, add a check to avoid errors:
key_name_length = ndb.ComputedProperty(lambda e: len(e.key.id()) if isinstance(e.key.id(), str) else 0)
This checks if the key's ID is a string before calculating length, returning 0 for numeric IDs (you can adjust this fallback value if needed).
3. Named Function (Better for Edge Cases)
For more readability and easier error handling, use a named function instead of a lambda:
def calculate_key_name_length(self): try: # key.name() only returns string names (raises AttributeError for numeric IDs) return len(self.key.name()) except AttributeError: # Handle entities with numeric keys here return 0 # In your model definition key_name_length = ndb.ComputedProperty(calculate_key_name_length)
Why This Avoids Redundancy
All these approaches use the entity's existing Key data (which is already stored with every entity in Datastore) to compute the length on the fly when the entity is saved. You don't need to store the key as a separate string—no redundant data, just the computed value you need.
内容的提问来源于stack exchange,提问作者David_Hogan

