嵌套列表django

时间:2015-04-14 16:47:52

标签: python django list nested django-queryset

Assuiming

我有这样的一对多模型:

class User(models.Model):
     username = models.CharField(max_length=255)

class UserComment(models.Model):
     user = models.ForeignKey(User)
     text = models.CharField(max_length=255)

如何在django视图中创建一个查询集以获得如下列表?

user_comments= [[username1, [text1, text2, text3]], [username2, [text1, text2]]]

---- ---- UPDATE

我最终使用了稍微修改过的Sander van Leeuwen解决方案

views.py

user_comments = {}
user_comments = Comments.objects.select_related('envia')
comments_by_user = collections.defaultdict(list)
for 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

{% for key, values in comments_by_user.items %}
<ul class="chat-history" id="{{key}}-hist">
    {% for val in values%} 
        <li class="opponent unread">
        {% for 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 %}

2 个答案:

答案 0 :(得分:1)

这样的事情:

user_comments = []
for comment in UserComment.objects.select_related('user') \
                                  .order_by('user__username'):
    if user_comments and user_comments[-1][0] == comment.user.username:
        user_comments[-1][1].append(comment.text)
    else:
        user_comments.append([comment.user.username, [comment.text]])

答案 1 :(得分:1)

您是否有理由想要嵌套列表?

dict会更容易处理。例如:

user_comments = UserComment.objects.select_related('user')
comments_by_user = defaultdict(list)
for comment in users_comments:
    comments_by_user[comment.user.username].append(comment.text)

这将输出:

{'username1': ['comment', 'comment', ...], 'username2': ['comment', 'comment']}

如果你真的想要嵌套列表,你可以这样做:

comments_list = [[username, comments] for username, comments in comments_by_user.items()]