[Answered ]-Using Django, how do I add a foreign key column that references the same table?

2👍

As per https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey:

To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey(‘self’, on_delete=models.CASCADE).

The above code should be changed to:

from __future__ import unicode_literals

from django.db import models

# Create your models here.

class CollectionModel(models.Model):
    parent = models.ForeignKey('self', on_delete=models.CASCADE)

0👍

You need to add the below line to your model’s

parent = models.ForeignKey('self', blank=True, null=True)

So, your model looks like,

from __future__ import unicode_literals

from django.db import models

# Create your models here.

class CollectionModel(models.Model):
    parent = models.ForeignKey('self', blank=True, null=True)

Leave a comment