Search code examples
google-app-enginegoogle-cloud-datastorewebapp2

Getting one of the key's fields instead of the full key


I have a Candidate model

class Candidate(ndb.Model):
    name = ndb.StringProperty()
    phone = ndb.StringProperty()
    location_name = ndb.StringProperty()
    state = ndb.KeyProperty(kind=Setting)

Model called Submission State

class SubmissionState(ndb.Model):
    name = ndb.StringProperty(required=True)
    description = ndb.TextProperty()

Model Setting is used to handle the settings based on a category that the user selected. All of this works fine.

Here is views.py. There is also a post method, but I am not sure if that's necessary here.

class EditSubmission(webapp2.RedirectHandler):

    def get(self):
        candidateid = self.request.path.split('/')[-1]
        candidate = Candidate._get_by_id(int(candidateid))
        template_values = {'candidate': candidate, }
        path = os.path.join(os.path.dirname(__file__), '../templates/edit_submission.html')
        self.response.write(template.render(path, template_values))

here is the template part:

    <tr>
        <th><label for="id_state">Submission State:</label></th>
        <td><input id="id_state" type="text" name="state" value="{{ candidate.state.name }}"/></td>
    </tr>

If I do {{ candidate.state }} I get the key and all of the fields, but I can not get only the name for some reason. How would I do that?

thanks.


Solution

  • candidate.state is just the key that points to the SubmissionState. Your app needs to make another request to the datastore to fetch the SubmissionState entity, like this:

    state_name = candidate.state.get().name
    

    You can perform that get() in your handler, and then add state_name into your template values so it's available within the template.