Can I Make a foreignKey to same model in django?

DjangoDjango Models

Django Problem Overview


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 ?

Django Solutions


Solution 1 - Django

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

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

Solution 2 - Django

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'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNuno_147View Question on Stackoverflow
Solution 1 - DjangoYuji 'Tomita' TomitaView Answer on Stackoverflow
Solution 2 - DjangoHedde van der HeideView Answer on Stackoverflow