Opened 18 years ago

Closed 18 years ago

Last modified 18 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: no UI/UX: no

Description

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):
    pass
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 by James Bennett, 18 years ago

Questions about how Django works are more properly addressed to the django-users mailing list (http://groups.google.com/group/django-users/).

And there's an example of relating a model to itself in the documentation; see here: http://www.djangoproject.com/documentation/models/m2o_recursive/

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 by Adrian Holovaty, 18 years ago

Resolution: worksforme
Status: newclosed

comment:3 by anonymous, 18 years ago

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