#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 , 19 years ago
comment:2 by , 19 years ago
Resolution: | → worksforme |
---|---|
Status: | new → closed |
comment:3 by , 19 years ago
Thank you. This was a RTFM error on my part. I missed this when digging for it.
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'.