Linking to entity from list

2019-03-02 16:55发布

问题:

I have a Consults page that lists consults in the datastore. The list loop is like this:

{% for consult in consults %}
 <tr>
  <td><a href="consults/#">{{ consult.consult_date }}</a></td>
  <td>{{ consult.consult_time }}</td>
  <td>{{ consult.patient_first }}</td>
  <td>{{ consult.patient_last }}</td>
  <td><span class="badge badge-warning">{{ consult.consult_status }}</span></td>
 </tr>
{%endfor%}

The handler is like this:

class ConsultsPage(webapp2.RequestHandler):
    def get(self):
        consults = Consults.query().fetch(5)
        consults_dic = {"consults" : consults}
        template = JINJA_ENVIRONMENT.get_template('/templates/consults.html')
        self.response.out.write(template.render(**consults_dic))

I want to know the basic concept behind how I make each consult in the list a link to go in and view information about that particular consult.

I understand I need to use a key to retrieve an entity but am unsure of the rest of the process.

Edit I have added the line:

url = '/display_consult?key=%s' % consults.key.urlsafe()

to my ConsultsPage (where the consults are listed). The handler now looks like this:

class ConsultsPage(webapp2.RequestHandler):
    def get(self):
        consults = Consults.query().fetch(5)
        consults_dic = {"consults" : consults}
        url = '/display_consult?key=%s' % consults.key.urlsafe()
        template = JINJA_ENVIRONMENT.get_template('/templates/consults.html')
        self.response.out.write(template.render(**consults_dic))

However I get this error:

url = '/display_consult?key=%s' % consults.key.urlsafe()
AttributeError: 'list' object has no attribute 'key'

Also what do I put into the link href in my loop that lists consults? is it something like:

href="consults/{{ url }}"

回答1:

From Retrieving Entities from Keys:

You can also use an entity's key to obtain an encoded string suitable for embedding in a URL:

url_string = sandy_key.urlsafe()

This produces a result like agVoZWxsb3IPCxIHQWNjb3VudBiZiwIM which can later be used to reconstruct the key and retrieve the original entity:

sandy_key = ndb.Key(urlsafe=url_string)
sandy = sandy_key.get()

So for each consult entity you can obtain a unique URL where you'd display the info about that entity. For example by using a URL parameter:

url = '/display_consult?key=%s' % consult.key.urlsafe()

And in the /display_consult page handler you'd obtain the entity like this:

consult = ndb.Key(urlsafe=request.get('key')).get()