Home:ALL Converter>Django Simple History - History Diffing

Django Simple History - History Diffing

Ask Time:2019-05-15T17:39:33         Author:Kevin D.

Json Formatter

So I'm using django-simple-history for one of my projects. I'm using it on one of the models called "Address" to show the history of the records.

I've created a DetailView to show the information about the address and added context['history'] to show changes of the record. This works all fine.

I would be interested in what field changed, and I read the following; History Diffing

So I somehow need to loop through all the fields from the last two records and find the field which has changed...

I couldn't find any examples on how to achieve this so I tried adding the context to the view

#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

And a simple model

#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)

Template

#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>

Somehow this doesn't feel right, there should be a way to iterate over the changes and only add the changed fields to the context...

Any ideas would be appreciated!

Author:Kevin D.,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56146175/django-simple-history-history-diffing
yy