How do I sort a query object which is a StringListProperty()?
I have this model:
class ArticleTagList(db.Model):
article_tags = db.StringListProperty()
In the EditArticleHandler
I do:
tag_query = ArticleTagList.all()
for tag in tag_query:
for i in range(len(tag.article_tags)):
self.response.out.write(""" <span id="small-tags">
<input type="checkbox" name="article_tag" value="%s">%s </span>"""
% (tag.article_tags[i], tag.article_tags[i]))
But it would be nice to print these tags in alpabetical order.
Of course trying
tag_query.sort()
gives
AttributeError: 'Query' object has no attribute 'sort'
How do I sort the queried list? Thanks.
Update
Thanks for the answers. I am having difficulty understanding query results so not sure I understand the comments below; but this is how I solved it and I would appreciate comments why this a good solution or 开发者_Go百科why it is not a good solution. (for instance, is it still wrong to use range()
to iterate?) Thanks!
query = ArticleTagList.all()
items = query.get()
items.article_tags.sort()
for i in range(len(items.article_tags)):
self.response.out.write(""" <span id="small-tags">
<input type="checkbox" name="article_tag" value="%s">%s </span>"""
% (items.article_tags[i], items.article_tags[i]))
You probably want:
for article_tag_list in tag_query:
article_tags = sorted(article_tag_list.article_tags)
for tag in article_tags:
self.response.out.write("""<span id="small-tags">
<input type="checkbox" name="article_tag" value="%s">%s </span>"""
% (tag, tag))
It sounds like you're trying to print the tags in order, but you're attempting to sort the instances, instead. You should be doing something like this:
for taglist in tag_query:
for tag in sorted(taglist.article_tags):
#...
But given that you probably always want them in sorted order, it'd be easier to call taglist.article_tags.sort()
on the entity when you create it, and before you store it, to ensure the tags are stored in sorted order.
Please don't iterate through a list by doing for i in range(len(tag.article_tags))
. There's no reason for it. for tag in tag.article_tags
works much better and is more Pythonic.
To answer your question though, don't forget you have two list-like things here: the set of ArticleTagList
instances, and the list of article_tags
within each instance. Are you trying to sort all the tags, no matter which taglist they are in? In which case, you will need to join them all into one big list:
full_list = []
for tag in tag_query:
full_list.extend(list(tag.article_tags))
full_list.sort()
精彩评论