Django 3.2 -> 4.2 - PK serialize=False migration (even when True)

Hi,

I’m bumping a project from 3.2 to 4.2.
Post version bump, django wants to generate a new migration for a model (there are no model changes).
This model has a composite primary key of a timestamp + id (django doesn’t need to know or care about this).
In the model definition the timestamp field is models.DateTimeField(primary_key=True).
Post bump django detects changes to model in the app and wants to generate an alter field migration to set
name=“timestamp”,
field=models.DateTimeField(primary_key=True, serialize=False),

I don’t necessarily want the timestamp field to be excluded from serialization. But setting serialize=True in the model definition and in historical migrations has no effect and django still wants to generate a new migration with serialize=False.

Can anyone help me understand what is happening here?

I can see that in django/db/models/options.py

def setup_pk(self, field):
    if not self.pk and field.primary_key:
        self.pk = field
        field.serialize = False

Is there a rationale for Django forcing field.serialize = False

I think it’s covered at Serializing Django objects | Django documentation | Django

The primary key is always serialized as the pk element in the resulting output; it never appears in the fields part.

1 Like

I didn’t find any changes related to this in the documentation, but manual testing shows that Django 4.0’s autodetector does detect this.