I have the following model classes:
class Collection(db.Model):
name = db.StringProperty()
text_keys = db.ListProperty(db.Key)
class Text(db.Model):
name = db.StringProperty()
content = db.StringProperty()
and I’m trying to do the following:
class Collections(webapp.RequestHandler):
def get(self):
collections = model.Collection.all() # works fine
for c in collections:
c.number_of_texts = len(c.text_keys) # does not work
template_values = {
'collections': collections,
}
I’m certainly no python-expert, but shouldn’t this work?
UPDATE:
By does not work i mean that the variable number_of_texts is not added to the model object.
In my django-template, the following code generates nothing, except for the collection name:
{% for c in collections %}
<p>{{c.name}}, number of texts: {{c.number_of_texts}}</p>
{% endfor %}
SOLUTION:
Thanks to RocketDonkey for pointing out that this can be done in a more elgant fashion using django formatting:
{% for c in collections %}
<p>{{c.name}}, number of texts: {{c.text_keys|length}}</p>
{% endfor %}
or by passing a separate dictionary with the names and lenghts to the template, if a similar problem with no good formatting solution should occur.
So it appears that you are trying to write to the
number_of_textsproperty of theCollectionmodel (which does not exist 🙂 ). If you just need to get the number of items in that list element, you’ll need to store it in a separate variable not tied toc:In order to add the length of the list to your document (assuming you don’t need it anywhere else), try using the
lengthfunction in your template:This may not work depending on your templating engine (I have only used one so I’m far from an expert), but it will hopefully get you what you want.