Can I Make a foreignKey to same model in django?

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 ?


Solution 1:

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

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

Solution 2:

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'