python - Nested list django -
assuiming
i have 1 many model this:
class user(models.model): username = models.charfield(max_length=255) class usercomment(models.model): user = models.foreignkey(user) text = models.charfield(max_length=255)
how can make queryset in django view in order have list following?
user_comments= [[username1, [text1, text2, text3]], [username2, [text1, text2]]]
----update----
i ended using modified version of sander van leeuwen solution
views.py
user_comments = {} user_comments = comments.objects.select_related('envia') comments_by_user = collections.defaultdict(list) comment in user_comments: comments_by_user[comment.envia.id].append([comment.envia.first_name+" "+comment.envia.last_name,comment.text,comment.date.strftime('%d/%m/%y')]) comments_by_user.default_factory = none
template.html
{% key, values in comments_by_user.items %} <ul class="chat-history" id="{{key}}-hist"> {% val in values%} <li class="opponent unread"> {% v in val %} {%if forloop.counter = 1 %} <span class="user">{{v}}</span> {% elif forloop.counter = 2 %} <p>{{v}}</p> {% elif forloop.counter = 3 %} <span class="time">{{v}}</span> {%endif%} {% endfor %} </li> {% endfor %} </ul> {% endfor %}
is there reason want nested lists?
a dict easier deal with. example:
user_comments = usercomment.objects.select_related('user') comments_by_user = defaultdict(list) comment in users_comments: comments_by_user[comment.user.username].append(comment.text)
this output:
{'username1': ['comment', 'comment', ...], 'username2': ['comment', 'comment']}
if want nested lists can do:
comments_list = [[username, comments] username, comments in comments_by_user.items()]
Comments
Post a Comment