【问题标题】:Nested list django嵌套列表 Django
【发布时间】:2015-06-20 09:31:33
【问题描述】:

假设

我有一个这样的一对多模型:

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]]]

----更新----

我最终使用了 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 %}

【问题讨论】:

    标签: python django list nested django-queryset


    【解决方案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()]
    

    【讨论】:

      【解决方案2】:

      类似这样的:

      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]])
      

      【讨论】:

        猜你喜欢
        • 2014-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 2021-03-01
        相关资源
        最近更新 更多