Search code examples
djangodjango-simple-history

How do I save a Historical field on a non-historical model in Django Simple History?


I have something like a ContractTemplate shared for all clients which is 'versioned' through django-simple-history. I have a ClientContract that I want to attach a HistoricalContractTemplate as a field, so I can tell what the ContractTemplate looked at the time the ClientContract was created.

class ContractTemplate(models.Model):
   text = models.TextField()
   
    # Create model 'HistoricalContractTemplate' which stores all changes
    history = HistoricalRecords()


class ClientContract(models.Model):
   client_text = models.TextField()

   contract_template_version = ???? # <------

And after I set up the model right, how do I use it?

def update_client_contract(contract_template_that_will_get_stale):
    # ... update other client contract fields

    newest_history_record_of_this_contract_template = ??? # <---
    client_contract.contract_template_version= newest_history_record_of_this_contract_template

Solution

  • It is possible to access the .model of the .history which is a model that django-simple-history made itself:

    class ContractTemplate(models.Model):
        text = models.TextField()
        history = HistoricalRecords()
    
    
    class ClientContract(models.Model):
        client_text = models.TextField()
        contract_template_version = models.ForeignKey(
            ContractTemplate.history.model, on_delete=models.PROTECT
        )