Opened 12 years ago

Closed 12 years ago

Last modified 12 years ago

#1648 closed defect (worksforme)

How to ForeignKey to itself

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


Let's assume the following Model definition, which isn't necessarily useful by itself but illustrates the problem:

class Foo(meta.Model):
    parent = meta.ForeignKey(Foo, null=True, blank=True)

We hit a Python limitation: It is not possible to refer to the class name Foo during its definition. What should be done to resolve this?

I attempted to remedy by doing the following, but it didn't work:

class Foo(meta.Model):
Foo.parent = meta.ForeignKey(Foo, null=True, blank=True)

There is no parent field in a model thus defined.

1) This should work, shouldn't it? Why doesn't it work?

2) Is there a better way to construct self-referencing models?

Change History (3)

comment:1 Changed 12 years ago by James Bennett

Questions about how Django works are more properly addressed to the django-users mailing list (

And there's an example of relating a model to itself in the documentation; see here:

The trick is to use 'self' instead of 'Foo'; in Python, you can always reference a class from within itself by using 'self'.

comment:2 Changed 12 years ago by Adrian Holovaty

Resolution: worksforme
Status: newclosed

comment:3 Changed 12 years ago by anonymous

Thank you. This was a RTFM error on my part. I missed this when digging for it.

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