因此,我在我的一个项目中使用了django-simple-history。我在一个名为"Address“的模型上使用它来显示记录的历史记录。
我已经创建了一个DetailView来显示有关地址的信息,并添加了上下文“历史记录”来显示记录的更改。这一切都很好。
我会感兴趣的是字段发生了什么变化,并且我阅读了以下内容;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>不知何故,这感觉不太对,应该有一种方法来迭代更改,并只将更改的字段添加到上下文中……
任何想法都将不胜感激!
发布于 2019-12-10 22:15:08
我最近一直在做这件事。我认为你遗漏了一个技巧,你已经将更改存储在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 %}https://stackoverflow.com/questions/56146175
复制相似问题