Google Appengine: objects passed to a template changes their addresses in memory
I query an array of objects from DB, then compare addresses of the objects in Model and in View. They differs! Why? I want access the same objects as from template as from business logics code.
I wouldn't ask for it but it really bother me becau开发者_运维百科se function calls are disallowed in Django-styled templates and I even can't assign custom properties to DB-objects within the business logics code.
In request handler:
from google.appengine.ext.webapp import template
cats = db.GqlQuery("SELECT * FROM Cats")
for cat in cats:
self.response.out.write("<li>%s</li>" % (a))
In template:
{% for a in articles %}
{{a}},
{% endfor %}
Addresses (hash codes) differs in such code.
When you use the query iterator, you in fact do several fetches in sequence, each one will result in a new model instance.
Instead of doing:
cats = db.GqlQuery("SELECT * FROM Cats")
for cat in cats:
...
...do this instead:
cats = db.GqlQuery("SELECT * FROM Cats").fetch(50)
for cat in cats:
...
And pass the list of cats to the template. You will have same lists in handler and template, as each entity is loaded into a model instance only once.
精彩评论