所以我在我的一个项目中使用了django-simple-history。我在一种名为“地址”的模型上使用它来显示记录的历史记录。
我创建了一个DetailView以显示有关地址的信息,并添加了context ['history']以显示记录的更改。一切正常。
我会对哪个领域发生变化感兴趣,因此请阅读以下内容; History Diffing
所以我需要以某种方式遍历最后两个记录中的所有字段,并找到已更改的字段...
我找不到有关如何实现此目标的任何示例,因此我尝试将上下文添加到视图中
#views.py
class Address(DetailView):
'''
Show details about the address
'''
model = Address
'''
Add history context to the view and show latest changed field
'''
def get_context_data(self, **kwargs):
context = super(Address, self).get_context_data(**kwargs)
qry = Address.history.filter(id=self.kwargs['pk'])
new_record = qry.first()
old_record = qry.first().prev_record
context['history'] = qry
context['history_delta'] = new_record.diff_against(old_record)
return context
还有一个简单的模型
#models.py
class Address(models.Model)
name = models.CharField(max_length=200)
street = models.CharField(max_length=200)
street_number = models.CharField(max_length=4)
city = models.CharField(max_length=200)
模板
#address_detail.html
<table>
<thead>
<tr>
<th scope="col">Timestamp</th>
<th scope="col">Note</th>
<th scope="col">Edited by</th>
</tr>
</thead>
<tbody>
{% for history in history %}
<tr>
<td>{{ history.history_date }}</td>
<td>{{ history.history_type }}</td>
<td>{{ history.history_user.first_name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
以某种方式感觉不对,应该有一种方法可以迭代更改,仅将更改的字段添加到上下文中。
任何想法将不胜感激!
答案 0 :(得分:0)
我最近对此进行了研究。我认为您缺少将历史记录存储在history_delta中的技巧。您可以使用它来显示更改的字段。 下面将显示列表结果,例如更改了哪个字段以及该字段的旧值和新值。
{% if history_delta %}
<h3>Following changes occurred:</h3>
<table>
<tr>
<th>Field</th>
<th>New</th>
<th>Old</th>
</tr>
{% for change in delta.changes %}
<tr>
<td>
<b>{{ change.field }}</b>
</td>
<td>
<b>{{ change.new }}</b>
</td>
<td>
<b>{{ change.old }}</b>
</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No recent changes found.</p>
{% endif %}