嵌套列表djang

2024-10-03 09:21:04 发布

您现在位置:Python中文网/ 问答频道 /正文

阿苏明

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

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视图中创建一个queryset以获得如下列表?在

^{pr2}$

----更新----

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

视图.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

模板.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 %}

Tags: inforbymodelmodelscountercommentcomments
2条回答

你想要嵌套列表有什么原因吗?

口述会更容易处理。例如:

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)

这将输出:

^{pr2}$

如果确实需要嵌套列表,可以执行以下操作:

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

像这样:

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

相关问题 更多 >