Django self-referential foreign key


I’m kind of new to webapps and database stuff in general so this might be a dumb question. I want to make a model (“CategoryModel”) with a field that points to the primary id of another instance of the model (its parent).

class CategoryModel(models.Model):
    parent = models.ForeignKey(CategoryModel)

How do I do this? Thanks!

Asked By: sfendell



You can pass in the name of a model as a string to ForeignKey and it will do the right thing.


parent = models.ForeignKey("CategoryModel")

Or you can use the string “self”

parent = models.ForeignKey("self")
Answered By: Jared Forsyth

You can use the string ‘self’ to indicate a self-reference.

class CategoryModel(models.Model):
    parent = models.ForeignKey('self')

Answered By: Brandon Taylor

class Employee(models.Model):
    manager = models.ForeignKey('self', on_delete=models.CASCADE)


class Employee(models.Model):
    manager = models.ForeignKey("app.Employee", on_delete=models.CASCADE)

Answered By: Hailee

You also to set null=True and blank=True

class CategoryModel(models.Model):
    parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True)

null=True, to allow in database
blank=True, to allow in form validation

Answered By: Punnerud
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.