MikeN
MikeN

Reputation: 46367

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

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.

Upvotes: 70

Views: 18396

Answers (3)

You can do this using quotes too:

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

Upvotes: 2

ohnoes
ohnoes

Reputation: 5622

You should use

models.ForeignKey('self')

as mentioned here.

Upvotes: 125

Joe Holloway
Joe Holloway

Reputation: 28958

Yes, just do this:

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

Upvotes: 22

Related Questions