Code

Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#1648 closed defect (worksforme)

How to ForeignKey to itself

Reported by: alankila Owned by: adrian
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:

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?

Attachments (0)

Change History (3)

comment:1 Changed 8 years ago by ubernostrum

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 Changed 8 years ago by adrian

  • Resolution set to worksforme
  • Status changed from new to closed

comment:3 Changed 8 years ago by anonymous

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

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.