Can I have a Django model that has a foreign key reference to itself?

DjangoDjango Models

Django Problem Overview


Okay, how would I do this?

class Example(models.Model):
  parent_example = models.ForeignKey(Example)

I want to have a model have a foreign key reference to itself. When I try to create this I get a django validation error that Example is not yet defined.

Django Solutions


Solution 1 - Django

You should use

models.ForeignKey('self')

as mentioned here.

Solution 2 - Django

Yes, just do this:

class Example(models.Model):
  parent_example = models.ForeignKey('self')

Solution 3 - Django

You can do this using quotes too:

class Example(models.Model):
    parent_example = models.ForeignKey('Example')

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
QuestionMikeNView Question on Stackoverflow
Solution 1 - DjangoohnoesView Answer on Stackoverflow
Solution 2 - DjangoJoe HollowayView Answer on Stackoverflow
Solution 3 - DjangoUmut Çağdaş CoşkunView Answer on Stackoverflow