Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 315
Nuno_147 Avatar asked Jun 26 '12 18:06

Nuno_147


People also ask

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.

How do I create a one to many relationship in Django?

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.

What is the difference between ForeignKey and OneToOneField?

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.


2 Answers

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

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

like image 54
Yuji 'Tomita' Tomita Avatar answered Oct 12 '22 21:10

Yuji 'Tomita' Tomita


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'
like image 43
Hedde van der Heide Avatar answered Oct 12 '22 21:10

Hedde van der Heide