Can I make foreignKey for the same model in django?

Suppose I have this model:

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

Now I would like the task to be related 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 stating that the task is set. Is it "legal" if not, how can I do something like this?

+46
django django-models
Jun 26 '12 at 18:57
source share
2 answers
 class Task(models.Model): title = models.CharField() relates_to = models.ForeignKey('self') 

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

+89
Jun 26 '12 at 18:59
source share

Yes, you can do this, make the ForeignKey attribute a string:

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

In depth, you can also cross-reference the application model using dot notation, for example

 class Task(models.Model): title = models.CharField() relates_to = ForeignKey('<app_name>.Task') # eg 'auth.User' 
+15
Jun 26 '12 at 19:00
source share



All Articles