简体   繁体   中英

How to drill down from entity list to entity instance in Google Appengine?

I have a list of entities, and want to use the entity key to link to more details of an individual entity.

class RouteDetails(ndb.Model):
    """Get list of routes from Datastore """
    RouteName = ndb.StringProperty()

    @classmethod
    def query_routes(cls):
        return cls.query().order(-cls.RouteName)


class RoutesPage(webapp2.RequestHandler):
    def get(self):
        adminLink = authenticate.get_adminlink()
        authMessage = authenticate.get_authmessage()
        self.output_routes(authMessage,adminLink)

    def output_routes(self,authMessage,adminLink):
        self.response.headers['Content-Type'] = 'text/html'
        html = templates.base
        html = html.replace('#title#', templates.routes_title)
        html = html.replace('#authmessage#', authMessage)
        html = html.replace('#adminlink#', adminLink)
        html = html.replace('#content#', '')
        self.response.out.write(html + '<ul>')
        list_name = self.request.get('list_name')
        #version_key = ndb.Key("List of routes", list_name or "*notitle*")
        routes = RouteDetails.query_routes().fetch(20)

        for route in routes:
            routeLink = '<a href="route_instance?key={}">{}</a>'.format(
                route.Key, route.RouteName)
            self.response.out.write('<li>' + routeLink + '</li>')
        self.response.out.write('</ul>' + templates.footer)

The error I am getting is AttributeError: 'RouteDetails' object has no attribute 'Key' .

How do I reference the unique ID of the entity in my drilldown URL?

The RouteDetails object indeed has not Key attribute, so you will get an exception at route.Key .

To get an entity's key you need to invoke the key attribute/property: route.key .

But passing the entity's key directly through HTML does not work since it's an object. The urlsafe() method is available to provide a string representation of the key object that is OK to use in HTML.

So do something along these lines instead:

    for route in routes:
        routeLink = '<a href="route_instance?key={}">{}</a>'.format(
            route.key.urlsafe(), route.RouteName)
        self.response.out.write('<li>' + routeLink + '</li>')

See also Linking to entity from list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM