django group by in template

时间:2015-02-12 22:10:37

标签: django group-by

我正在尝试记录用户的记录更改历史记录。 我有一个历史模型:

class History(models.Model):
concerning      = models.ForeignKey(User)
field           = models.CharField(max_length=30)
creation_date   = models.DateTimeField(auto_now_add=True)
author          = models.ForeignKey(User, related_name='autor_history_info')
action          = models.CharField(max_length=30)
new_value       = models.CharField(max_length=1000)

和历史记录视图:

def get_history(request):
changes = History.objects.all().filter(concerning=request.user).order_by('field')

return render(request, "get_history.html", {"changes" : changes)

和历史记录模板:

{%for change in changes %}
  <h1>{{change.field}} </h1>
  {{change.creation_date}} 
  {{change.author}}
  {{change.action}}
  to
  {{change.new_value}}
  <br>
{% endfor %}

我遗憾地找不到制作组的好方法,这将限制一次显示该字段,然后是下面的所有更改。如何组成这样做?

1 个答案:

答案 0 :(得分:2)

使用{% ifchanged %}模板标记:

{% for change in changes %}

  {% ifchanged %}<h1>{{change.field}}</h1>{% endifchanged %}

  {{change.creation_date}} 
  {{change.author}}
  {{change.action}}
  to
  {{change.new_value}}
  <br>

{% endfor %}