In my application, I have a model DataSeriesModel and my migration file for this model looks like this:
migrations.CreateModel(
name='DataSeriesModel',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('id', model_utils.fields.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=255)),
...
After adding history = HistoricalRecords() field to the model and running makemigrations I'm getting another migrations file with the content as follows:
operations = [
migrations.CreateModel(
name='HistoricalDataSeriesModel',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('id', model_utils.fields.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True)),
('name', models.CharField(max_length=255)),
...
('history_id', models.AutoField(primary_key=True, serialize=False)),
('history_date', models.DateTimeField(db_index=True)),
('history_change_reason', models.CharField(max_length=100, null=True)),
('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)),
('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)),
],
There are two primary keys in this migration file and of course, after migrate command we're getting:
django.db.utils.ProgrammingError: multiple primary keys for table "data_series_models_historicaldataseriesmodel" are not allowed
LINE 1: ...cription" text NULL, "history_id" serial NOT NULL PRIMARY KE...
When I tried to manually set history_id to for example models.IntegerField() the migrate command worked without errors, but I didn't get any historical records in the database.
What could be wrong?
What can I try/change to get any historical records?
I had a similar issue while using the same
model_utilslib for the UUID fieldFirst of all,
history_idshould remain your primary key in order for history to work.Secondly:
model_utils.fields.UUIDFieldinherits asprimary_keyand manually set it toFalsedidn't provide any effect.So the solution: Replace
model_utils.fields.UUIDFieldwithmodels.UUIDField