Opened 10 years ago

Last modified 4 days ago

#22977 assigned Cleanup/optimization

No validation error when ForeignKey related_name clashes with manager name.

Reported by: Russell Keith-Magee Owned by: Anthony Joseph
Component: Core (System checks) Version: dev
Severity: Normal Keywords:
Cc: Mariusz Felisiak Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description

Consider the following model definition:

class Author(models.Model):
    authors = models.Manager()

    name = models.CharField(max_length=100)

    mentor = models.ForeignKey('self', related_name='authors')

The related name on the the foreign key clashes with the manager, so when you try to issue a query:

    Author.authors.filter(name__startswith='Douglas')

you get an error because "Author.authors has no attribute 'filter'".

The problem is order dependent; if you define the manager *after* the foreign key, you get different errors.

I haven't checked what errors you get if you just have the default Manager, and a related_name of 'objects'.

There may also be problems if you have a field named 'objects'.

I suspect this class of problem could be picked up by the system check framework.

Change History (9)

comment:1 by Konrad Świat, 10 years ago

Owner: changed from nobody to Konrad Świat
Status: newassigned

comment:2 by Konrad Świat, 10 years ago

Has patch: set

comment:3 by Tim Graham, 10 years ago

Patch needs improvement: set

As Loic noted on the PR, we should revisit this after the _meta factor is merged.

comment:4 by Konrad Świat, 10 years ago

Owner: Konrad Świat removed
Status: assignednew

comment:5 by Davide Ceretti, 10 years ago

Owner: set to Davide Ceretti
Status: newassigned
Version: 1.6master

comment:6 by Davide Ceretti, 10 years ago

Given loic's comment at https://github.com/django/django/pull/3359#issuecomment-59642918, what would be the correct implementation of this validation check? Adding it to BaseManager.check method?

comment:7 by Mariusz Felisiak, 3 years ago

Owner: Davide Ceretti removed
Status: assignednew

comment:8 by Anthony Joseph, 4 days ago

Owner: set to Anthony Joseph
Status: newassigned

comment:9 by Mariusz Felisiak, 4 days ago

Cc: Mariusz Felisiak added
Note: See TracTickets for help on using tickets.
Back to Top