82

Assume I have this model :

class Task(models.Model):
    title = models.CharField()

Now I would like that a task may be relates to another task. So I wanted to do this :

class Task(models.Model):
    title = models.CharField()
    relates_to = ForeignKey(Task)

however I have an error which states that Task is note defined. Is this "legal" , if not, how should I do something similar to that ?

Nuno_147
  • 2,817
  • 5
  • 23
  • 36
  • If you don't want `relates_to` to link to itself, see http://stackoverflow.com/q/37946885/247696 – Flimm Jun 21 '16 at 14:15

2 Answers2

163
class Task(models.Model):
    title = models.CharField()
    relates_to = models.ForeignKey('self')

https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey

Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • 1
    Good idea with using `self` instead of 'Task'! – Mariusz Jamro Mar 13 '13 at 22:20
  • 1
    Suppose I use something like this and want to delete Tasks. Since each Task instance has a foreignkey to another Task instance, if I delete one Task instance will Django automatically cascade deletes so it auto deletes any Task instance that points to the Task I just deleted? In other words, does CASCADE DELETE still work within the same model? – Marc Dec 10 '14 at 01:59
  • 1
    @Marc I haven't confirmed specifically, but that would be the behavior I expect. With Django, I'm more worried about specifically having to prevent the cascading delete than ensuring it happens. – Yuji 'Tomita' Tomita Dec 10 '14 at 04:30
  • 1
    Yes you can write it as `models.ForeignKey('self', on_delete=models.CASCADE)` to ensure CASCADE DELETE behavior. – StanKosy Jan 29 '22 at 02:45
22

Yea you can do that, make the ForeignKey attribute a string:

class Task(models.Model):
    title = models.CharField()
    relates_to = ForeignKey(to='Task')

In depth, you can also cross reference an app's model by using the dot notation, e.g.

class Task(models.Model):
    title = models.CharField()
    relates_to = ForeignKey(to='<app_name>.Task')  # e.g. 'auth.User'
Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100