I am trying to create a string of the key of a ReferenceProperty within a webapp template:
Assume the following simple datastore model:
def User(db.Model):
first_name = StringProperty()
last_name = StringProperty()
def Email(db.Model):
user = ReferenceProperty(User)
email = EmailProperty()
I then pass a list of Email entities to a webapp template in list named member_list. Within the template, I want to create a string of the key of each Email entity’s ‘user’ property for use in a URL, such as:
{% for member in member_list %}
<a href="/member_handler/{{INSERT_STRING_OF_MEMBER.USER_KEY_HERE"}}>blah</a>
I realize I could pass a string of the key to the template, but I would prefer to do the string conversion in template if possible; I have tried various permutations of str() and _ str_ to no avail.
Since you know the entity in question will be a
Memberinstance, and presumably won’t have a parent entity, it’s much simpler (and produces nicer URLs) to use the key name or ID of the member, rather than the full string key. You can get this withuser.key().name()(user.key.namein a Django template) oruser.key().id(). Which one you need depends on whether you created the entity with a key name or not.If you have an email object, there’s no need to fetch the
Userfrom it just to get its key. Instead, callEmail.user.get_value_for_datastore(member), which will return theKeyobject of theUserit references. You can then extract the relevant field as you wish. There’s no way to do this in Django, though, so you’ll either need to do it outside Django and pass it in, or add a method to theEmailclass that returns the key.Once you have an ID or Name and want to fetch the
Userobject it references, callUser.get_by_id(id)orUser.get_by_key_name(name)as appropriate.