首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django简单历史-历史差异

Django简单历史-历史差异
EN

Stack Overflow用户
提问于 2019-05-15 17:39:34
回答 1查看 1.2K关注 0票数 1

因此,我在我的一个项目中使用了django-simple-history。我在一个名为"Address“的模型上使用它来显示记录的历史记录。

我已经创建了一个DetailView来显示有关地址的信息,并添加了上下文“历史记录”来显示记录的更改。这一切都很好。

我会感兴趣的是字段发生了什么变化,并且我阅读了以下内容;History Diffing

因此,我需要遍历最后两条记录中的所有字段,并找到已更改的字段…

我找不到任何如何实现这一点的示例,所以我尝试将上下文添加到视图中

代码语言:javascript
复制
#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

和一个简单的模型

代码语言:javascript
复制
#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)

模板

代码语言:javascript
复制
#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>

不知何故,这感觉不太对,应该有一种方法来迭代更改,并只将更改的字段添加到上下文中……

任何想法都将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2019-12-10 22:15:08

我最近一直在做这件事。我认为你遗漏了一个技巧,你已经将更改存储在history_delta中。您可以使用它来显示更改的字段。下面将显示列表结果,如更改了哪个字段以及该字段的旧值和新值。

代码语言:javascript
复制
{% 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 %}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56146175

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档