How to ForeignKey to itself
|Reported by:||alankila||Owned by:||adrian|
|Component:||Database layer (models, ORM)||Version:|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
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?