I am using the simple history library for my Django project. It's pretty nifty, but I'm having trouble showing aggregated history stats next to a base model object.
Here's what my model looks like:
from django.db import models
from django.contrib.auth.models import User
from simple_history.models import HistoricalRecords
class RepairForm(models.Model):
user_id = models.ForeignKey(User, on_delete=models.DO_NOTHING,)
return_number = models.CharField(max_length=200, unique=True)
status_id = models.ForeignKey(RFormStatus, on_delete=models.DO_NOTHING)
...
history = HistoricalRecords()
def __str__(self):
return self.return_number
The Docs lead me to believe the proper way of accessing historical records is using the history manager. I can get both sets of information I want:
All Forms (base model objects) -
RepairForm.objects.all()
User ID | Return Number | Status ID
-----------------------------------------------------------
33 | 0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 65001
44 | 5f699795-5119-4dcd-8b94-34f7056e732c | 65002
...
A history calculation (history object)
In this example I am getting the latest event of each form -
RepairForm.history.all()\
.values('return_number').annotate(latest_event_date=Max('history_date'))\
.order_by('return_number')
Return Number | latest_event_date
-----------------------------------------------------------
0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 7/27/2018
5f699795-5119-4dcd-8b94-34f7056e732c | 8/1/2018
...
I feel like this should be possible to do in one query though no? One query that outputs something like this:
User ID | Return Number | Status ID | latest_event_date
------------------------------------------------------------------------------
33 | 0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 65001 | 7/27/2018
44 | 5f699795-5119-4dcd-8b94-34f7056e732c | 65002 | 8/1/2018
...