Search code examples
pythondjangodjango-orm

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!


Solution

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

    So:

    parent = models.ForeignKey("CategoryModel")
    

    Or you can use the string "self"

    parent = models.ForeignKey("self")