Hi all,
I’m working on a documentation improvement related to ticket #35877, which highlights that when switching from an implicit ManyToManyField
to a custom through
model, Django no longer automatically creates a unique index on the foreign keys.
The current migration example in docs/howto/writing-migrations.txt uses SeparateDatabaseAndState
to rename the table and preserve data, but it doesn’t mention the loss of the unique constraint.
I’ve updated the CreateModel
operation to include:
options={
"constraints": [
models.UniqueConstraint(
fields=["author", "book"],
name="unique_author_book",
)
],
}
And added a note below the migration example:
.. note::
When switching from an implicit `ManyToManyField` to a custom through model,
Django does not automatically preserve the unique index on the foreign keys.
To maintain the same behavior, add a `UniqueConstraint` in the migration.
This ensures consistent behavior across database backends and avoids subtle bugs.
The older `unique_together` option is deprecated and should be avoided.
Would love feedback on whether this change aligns with the ticket’s intent and Django’s documentation standards.