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

I think you need to set the model up as a foreign key, but use the text class name instead of importing it (not sure if it is possible to import it)

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

   # I used protect because hopefully history records aren't being deleted
   contract_template_version = models.ForeignKey('HistoricalContractTemplate', models.PROTECT, null=True)

And then since .history filters to the history of only the current instance of the client contract, I think you can do this:

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

    newest_history_record_of_this_contract_template = contract_template_that_will_get_stale.history.order_by("history_date").first()
    client_contract.contract_template_version= newest_history_record_of_this_contract_template

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)
Вернуться на верх