有一种方法可以从jinja2模板访问ndb模型类属性

时间:2012-06-14 16:08:49

标签: google-app-engine app-engine-ndb

我正在使用Appengine 1.6.5,从jinja2模板访问NDB模型类属性我没有,而是我得到了正确的结果,在循环中访问相同的属性。 解释我发布一些代码的问题

---模特---

class Vehicles(ndb.Model):
    registration = ndb.StringProperty()
    brand = ndb.StringProperty()
    model = ndb.StringProperty()
    cost = ndb.FloatProperty()
    km_cost = ndb.FloatProperty()
    viacard = ndb.StringProperty()
    telepass = ndb.StringProperty()

class Employees(ndb.Model):
    user_id = ndb.StringProperty()
    name = ndb.StringProperty()
    surname = ndb.StringProperty()
    email = ndb.StringProperty()
    job = ndb.StringProperty()
    credit_card = ndb.StringProperty()
    cc_expiry_date = ndb.StringProperty()
    vehicle = ndb.KeyProperty(kind=Vehicles)
    last_login = ndb.DateTimeProperty(auto_now=True)
    last_activity = ndb.DateTimeProperty(auto_now=True)

    @property
    def vehicle_registration(self):
        return Key(self.vehicle.kind(),int(self.vehicle.id())).get().registration

---处理程序--- 这只是处理程序的一部分

class BaseHandler(webapp2.RequestHandler):

    @webapp2.cached_property
    def jinja2(self):
        return jinja2.get_jinja2(app=self.app)

    def render_template(self, filename, **kwargs):
        self.response.write(self.jinja2.render_template(filename, **kwargs))

class EmployeesHandler(BaseHandler):
    @login_required
    def get(self,**kwargs):
        user = users.get_current_user()
        company = models.Company.query().fetch(1)
        employees = models.Employees.query().fetch()
        vehicles = models.Vehicles.query().fetch()

        params = {
            "nickname" : user.nickname(),
            "company" : company,
            "employees" : employees,
            "vehicles" : vehicles
            }
        return self.render_template('employee.html', **params)

---模板--- 这是templte的一部分

<table class="table table-striped table-bordered table-condensed">
  <thead>
    <tr>
      <th>Nome</th>
      <th>Cognome</th>
      <th>Email</th>
      <th>Ruolo</th>
      <th>Carta di credito</th>
      <th>Scadenza</th>
      <th>Auto</th>
      <th>Ultimo accesso</th>
      <th>Ultimo movimento</th>
    </tr>
  </thead>
  <tbody>
    {% for emp in employees %}
    <tr>
      <td>{{ emp.name }}</td>
      <td>{{ emp.surname }}</td>
      <td>{{ emp.email }}</td>
      <td>{{ emp.job }}</td>
      <td>{{ emp.credit_card }}</td>
      <td>{{ emp.cc_expiry_date }}</td>
      <td>({{ emp.vehicle.vehicle_registration }})</td>
      <td>{{ emp.last_login }}</td>
      <td>{{ emp.last_activity }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

有人能告诉我正确的方法来获得雇员的汽车注册号吗? 提前谢谢

此致 罗伯特

1 个答案:

答案 0 :(得分:0)

尝试:emp.vehicle.get.vehicle_registration

但是,您正在遇到n+1 problem,您应该真正关注prefetching the vehicle reference.