Search code examples
pythondjangodjango-simple-history

Django model history by date and datetime


Assume I have model like this:

class Account(models.Model):
    balance = models.IntegerField()
    debt = models.IntegerField()
    history = HistoricalRecords()

I'm using django-simple-history to get instance of the model as it would have existed at the provided date and time:

inst = Account.history.as_of(datetime.datetime.now().date)

It's working fine, but I want to get instance where balance field is represented as it would have existed at the provided date and time, and then debt field will be most recent of that date. I don't know if this is possible, didn't find anything about that.


Solution

  • The history ORM will return back a model based off of the one you submitted, as it existed at that point in time.

    account = Account.objects.create(balance=1, debt=1)
    account.save()
    history_obj = account.history.last()
    print(history_obj.debt)  # returns 1
    
    account.debt = 222
    account.save()
    new_history_obj = account.history.last()
    print(new_history_obj.debt)  # returns 222
    

    Assuming you're using the Account.history.as_of() method to return the history object that you intend to be reading from, you could do this:

    yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
    history_obj = Account.history.as_of(yesterday)
    print(history_obj.debt)  # returns not the current debt, but the debt as-of yesterday
    

    Unless I'm misunderstanding what you're hoping to accomplish, you could just do this with what you have in your question:

    inst = Account.history.as_of(datetime.datetime.now().date)
    print(inst.debt)