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 ?
Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.
One to many relationships in Django models. To define a one to many relationship in Django models you use the ForeignKey data type on the model that has the many records (e.g. on the Item model). Listing 7-22 illustrates a sample of a one to many Django relationship.
A ForeignKey is a many-to-one relationship. So, a Car object might have many instances of Wheel . Each Wheel would consequently have a ForeignKey to the Car it belongs to. A OneToOneField would be like an instance of Engine , where a Car object has at most one and only one.
class Task(models.Model):
title = models.CharField()
relates_to = models.ForeignKey('self')
https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With