阿苏明
我有一个这样的一对多模型:
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 %}
你想要嵌套列表有什么原因吗?
口述会更容易处理。例如:
这将输出:
^{pr2}$如果确实需要嵌套列表,可以执行以下操作:
像这样:
相关问题 更多 >
编程相关推荐