Using pghistory with custom event table names

I'm currently testing pghistory for our Django project. I set up a few models to be tracked. As a convention our model names are different from the actual table names - these are defined in the Meta class like so:

class Delivery(models.Model):
    created = models.DateTimeField(auto_now_add=True, editable=False)
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='deliveries', on_delete=models.PROTECT, editable=False)
    ...

    class Meta:
        db_table = 'ep_delivery'

When I decorate the model with @pghistory.track() the resulting event table is called as the model, which is DeliveryEvent in this example. But I would rather have it being named ep_delivery_event to be in accordance with our conventions. How can I achieve this?

You can use the model_name option with pghistory.track to control the table name. So here it would be :

@pghistory.track(model_name="ep_delivery_event")

I found out that I can solve this by providing a custom event model:

https://django-pghistory.readthedocs.io/en/3.5.1/event_models/#configuration-with-pghistorytrack

Contrary to the other answer providing a model name does not solve this.

The code looks now something like this:

class Delivery(models.Model):
    created = models.DateTimeField(auto_now_add=True, editable=False)
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='deliveries', on_delete=models.PROTECT, editable=False)
    ...

    class Meta:
        db_table = 'ep_delivery'
BaseTrackedModelEvent = pghistory.create_event_model(Delivery)


class DeliveryEvent(BaseTrackedModelEvent):
    class Meta:
        db_table = 'ep_delivery_event'
Back to Top