Opened 9 years ago

Closed 9 years ago

#25027 closed Bug (duplicate)

two relations on the same model with same related_name break the model

Reported by: karyon Owned by: nobody
Component: Database layer (models, ORM) Version: 1.8
Severity: Normal Keywords:
Cc: karyon Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by karyon)

consider the following models:

class UserProfile(models.Model):
    pass

class Course(models.Model):
    participants = models.ManyToManyField(UserProfile, related_name='+')

class Document(models.Model):
    last_modified_user = models.ForeignKey(UserProfile, related_name='+')

and the following query:

>>> str(Course.objects.first().participants.all().query)
'SELECT "testapp_userprofile"."id" FROM "testapp_userprofile" INNER JOIN "testapp_document" ON ( "testapp_userprofile"."id" = "testapp_document"."last_modified_user_id" ) WHERE "testapp_document"."id" = 1'

the join doesn't make any sense to me. it makes both assertions in the following test fail:

def test_related_name(self):
    user = UserProfile.objects.create()
    course = Course.objects.create()
    course.participants = UserProfile.objects.all()
    self.assertEqual(course.participants.count(), 1)
    self.assertEqual(list(course.participants.all()), [user])

changing the related name in one of the models to something else fixes this.

if using a related name other than '+', the test still fails as before and the check command does not complain either, but at least makemigrations will spot the mistake.

Change History (3)

comment:1 by karyon, 9 years ago

Cc: karyon added

comment:2 by karyon, 9 years ago

Description: modified (diff)

comment:3 by Tim Graham, 9 years ago

Component: UncategorizedDatabase layer (models, ORM)
Resolution: duplicate
Status: newclosed

Duplicate of #24505 (currently fixed on master, but not 1.8).

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