We are using django-simple-history to track changes in our models, including many-to-many (m2m) relationships and generic relationships.
Model Configuration:
history = HistoricalRecords(
table_name="history_band_profiles",
history_user_setter=set_historical_user_from_request,
history_user_getter=get_historical_user_from_request,
history_user_id_field=models.CharField(max_length=36, null=True),
m2m_fields=[types], # Many-to-many tracking
)
Issues:
- Redundant History Records:
- When creating or updating resources, multiple redundant history entries are created
- This causes inaccurate historical data
- Tracking Generic Relationships:
- How can we retrieve historical data for GenericForeignKey relationships relevant to a resource
Expected Response Format: We need a structured response that includes the historical records of the resource, its many-to-many relations, and generic relations, like this (Field names are examples):
[
{
"id": 101,
"name": "Resource A",
"history_date": "2025-03-20T10:00:00Z",
"change_type": "update",
"types": [
{
"id": 201,
"name": "Sector X",
"history_date": "2025-03-19T15:00:00Z",
"change_type": "create"
},
{
"id": 202,
"name": "Sector Y",
"history_date": "2025-03-20T16:00:00Z",
"change_type": "update"
}
],
"generic_relation": [
{
"id": 301,
"type": "Document",
"title": "Policy Document A",
"history_date": "2025-03-18T11:00:00Z",
"change_type": "create"
},
{
"id": 302,
"type": "Document",
"title": "Policy Document B",
"history_date": "2025-03-20T14:00:00Z",
"change_type": "delete"
}
]
}
]
Notes:
- We tried using a through model for many-to-many relationships, but the history records do not maintain a link between the main model and the related objects
Are we missing something in our model configuration?
How can we ensure correct historical tracking for both m2m relationships and generic relationships?