#32983 closed Cleanup/optimization (fixed)

Prevent developers from defining a related_name on symmetrical ManyToManyFields

Reported by: Nick Touran Owned by: Nick Touran
Component: Database layer (models, ORM) Version: 4.0
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

In ManyToManyField, if the symmetrical argument is passed, or if it's a self-referential ManyToMany relationship, the related field on the target model is not created. However, if a developer passes in the related_name not understanding this fact, they may be confused until they find the information about symmetrical relationship. Thus, it is proposed to raise an error when the user defines a ManyToManyField in this condition.

Change History (9)

comment:1 Changed 13 months ago by Nick Touran

Owner: changed from nobody to Nick Touran
Status: newassigned

I have a PR that implements this incoming.

comment:3 Changed 13 months ago by Carlton Gibson

Patch needs improvement: set
Triage Stage: UnreviewedAccepted

OK, I guess we can do something here — it probably is a source of confusion.

The same issue was raised in #18021 (but as an invalid bug report, rather than suggesting improving the messaging).

Looking at the PR — I'm sceptical about just raising an error — this will likely break code in the wild.

Can we investigate adding a system check here instead?
There are several similar checks for related fields already: https://docs.djangoproject.com/en/3.2/ref/checks/#related-fields

comment:4 Changed 13 months ago by Carlton Gibson

Same issue also came up in #12641

comment:5 Changed 13 months ago by Nick Touran

Absolutely. A system check is a much better approach than my initial idea of the error. I have changed the patch to use a system check.

comment:6 Changed 13 months ago by Nick Touran

Patch needs improvement: unset

Unchecking patch needs improvement as instructed on the page, (pending reviewer acceptance of course).

comment:7 Changed 12 months ago by Carlton Gibson

Triage Stage: AcceptedReady for checkin

comment:8 Changed 12 months ago by Carlton Gibson <carlton@…>

In 1fb21ab3:

Refs #32983 -- Removed unneeded related_name from test model definitions.

comment:9 Changed 12 months ago by Carlton Gibson <carlton@…>

Resolution: fixed
Status: assignedclosed

In 5d4f21b1:

Fixed #32983 -- Added system check for redundant related_name on symmetrical M2M fields.

Since ManyToManyFields defined with symmetrical=True do not add a
related field to the target model, including a related_name argument
will never do what the coder likely expects. This makes including
a related_name with a symmetrical model raise a system check warning.

ticket-32983

Note: See TracTickets for help on using tickets.
Back to Top