Search code examples
django-simple-history

How to tell if a model has simple-history records?


I need a way to tell if a model has simple-history HistoricalRecord.

A bad way is to check is seeing if self.history exists but I don't like that because the developer doesn't have to use use history as the attribute name for the HistoricalRecord.

Alternatively I could try to loop through dir(model) but this runs into issues where a related name reverse lookup could result in a DoesNotExist exception. I could try to catch the exception but ugh that is ugly.

I need this because I'd like to add a link in django admin to a special view I made to look at simple history records and I want to display the link only if the model has HistoricalRecords.


Solution

  • After some digging around, it appears that simple-history keeps a record of all the models that have historical objects! How convenient! The solution to this problem can be something like

    from simple_history import models
    
    def has_simple_history(obj):
        return obj.__class__ in models.registered_models.values()