Opened 43 hours ago

Last modified 7 hours ago

#35877 assigned Cleanup/optimization

Documentation on "Changing a ManyToManyField to use a through model" does not respect database index

Reported by: robwa Owned by: Aditya Chaudhary
Component: Documentation Version: dev
Severity: Normal Keywords:
Cc: Adam Johnson, Mariusz Felisiak Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When creating a manytomany field with an implicit through table, a unique index is created on the database side for the through table for the two foreign keys. This fact is not respected in the documentation on Changing a ManyToManyField to use a through model. When using the proposed code, Django loses track of the index.

The addition of a simple options statement in the migration may be sufficient:

    // ...
    operations = [
        migrations.CreateModel(
            name="AuthorBook",
            // ...
            options={
                "unique_together": {("author", "book")},
            },
        ),
    ]

I have not been able to check comprehensively how different database systems behave when interacting with Django and in the context of renaming the table. SQLite retains the index, but it is not renamed. In the case of PostgreSQL, there were later bugs in an implementation that were difficult to find.

Change History (2)

comment:1 by Sarah Boyce, 41 hours ago

Cc: Adam Johnson Mariusz Felisiak added
Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization
Version: dev

This was added as part of a9ee6872bd9e1bacc2da827dbd5b9093f724e4a5 to give a solid example of using SeparateDatabaseAndState
That being said, I'm not against us adding an index and so accepting (I think it should be a UniqueConstraint as we recommend folks don't use unique_together anymore).
I will cc some folks who were involved in this section in the docs and see what they think also

            // ...
            options={
                "constraints": [
                    models.UniqueConstraint(
                        fields=["author", "book"],
                        name="unique_author_book",
                    )
                ]
            },

comment:2 by Aditya Chaudhary, 7 hours ago

Owner: set to Aditya Chaudhary
Status: newassigned
Note: See TracTickets for help on using tickets.
Back to Top