Django self-referential foreign key

PythonDjangoDjango Orm

Python Problem Overview


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!

Python Solutions


Solution 1 - Python

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")

Solution 2 - Python

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

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

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

Solution 3 - Python

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

Solution 4 - Python

https://books.agiliq.com/projects/django-orm-cookbook/en/latest/self_fk.html

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

OR

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

https://stackabuse.com/recursive-model-relationships-in-django/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsfendellView Question on Stackoverflow
Solution 1 - PythonJared ForsythView Answer on Stackoverflow
Solution 2 - PythonBrandon TaylorView Answer on Stackoverflow
Solution 3 - PythonPunnerudView Answer on Stackoverflow
Solution 4 - PythonHaileeView Answer on Stackoverflow