【问题标题】:How to drill down from entity list to entity instance in Google Appengine?如何在 Google Appengine 中从实体列表向下钻取到实体实例?
【发布时间】:2023-03-07 02:34:02
【问题描述】:

我有一个实体列表,并希望使用实体键链接到单个实体的更多详细信息。

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)

我得到的错误是AttributeError: 'RouteDetails' object has no attribute 'Key'

如何在我的drilldown URL 中引用实体的唯一 ID?

【问题讨论】:

  • key 全部小写。

标签: python entity-framework google-app-engine


【解决方案1】:

RouteDetails 对象确实没有Key 属性,所以你会在route.Key 处得到一个异常。

要获取实体的密钥,您需要调用key 属性/属性:route.key

但是直接通过 HTML 传递实体的键是行不通的,因为它是一个对象。 urlsafe() 方法可用于提供可以在 HTML 中使用的键对象的字符串表示形式。

因此,请按照以下方式做一些事情:

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

另见Linking to entity from list

【讨论】:

  • 我这样做了,但出现以下错误:routeLink = '&lt;a href="route_instance?key={}"&gt;{}&lt;/a&gt;'.format(route.key().urlsafe(), route.RouteName) TypeError: 'Key' object is not callable
  • 糟糕,key 是一个属性,而不是一个方法。固定。
  • 啊,所以urlsafe() 是一种应用于key 属性的方法。谢谢!
  • 是的,实体的key属性实际上是对应于该实体的ndb.Key对象。 可能最初误导了你。
  • 这就是我使用Key而不是key的原因,是的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
相关资源
最近更新 更多