Opened 12 years ago

Closed 11 years ago

#2608 closed defect (fixed)

multi-level foreignkey throws KeyError

Reported by: Gopal Narayanan <gopastro@…> Owned by: Adrian Holovaty
Component: contrib.admin Version:
Severity: minor Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


Example models:

class person(models.Model):
    pid = models.CharField(maxlength=20,
    name = models.CharField(maxlength=100)

class student(models.Model):
    student_pid = models.ForeignKey(person,

class student_option(models.Model):
    pid = models.ForeignKey(student,
    junk = models.IntegerField()

Note that student_option pid refers to student_pid which itself is a ForeignKey on student pointing to person.
Trying to generate SQL for these models throws KeyError: 'ForeignKey'

It appears that FKs are not allowed to point at a datatype that is itself a FK. It would be nice to allow multi-level foreign keys as there is a benefit in modeling legacy data with this kind of schema.

The patch attached simply enables the creation of SQL necessary for this to happen, by recursively diving down until we find the real underlying datatype.

Attachments (2)

multilevel_fk_patch.txt (628 bytes) - added by Gopal Narayanan <gopastro@…> 12 years ago.
multilevel_fk_patch.patch (710 bytes) - added by Chris Beaven 11 years ago.
slightly simpler patch

Download all attachments as: .zip

Change History (4)

Changed 12 years ago by Gopal Narayanan <gopastro@…>

Attachment: multilevel_fk_patch.txt added

Changed 11 years ago by Chris Beaven

Attachment: multilevel_fk_patch.patch added

slightly simpler patch

comment:1 Changed 11 years ago by Chris Beaven

Triage Stage: UnreviewedReady for checkin

Although this is an obscure use-case, I validated that this does raise the above exception and that the patch fixes this.

comment:2 Changed 11 years ago by Malcolm Tredinnick

Resolution: fixed
Status: newclosed

(In [5106]) Fixed #2608 -- Generate correct SQL for multi-level foreign key relations.
Based on a patch from Gopal Narayanan.

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