Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 468
MikeN Avatar asked Feb 10 '09 23:02

MikeN


People also ask

What is ForeignKey self in Django?

Self-referencing foreign keys are used to model nested relationships or recursive relationships. They work similar to how One to Many relationships. But as the name suggests, the model references itself. Self reference Foreignkey can be achived in two ways. class Employee(models.

How does ForeignKey work in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.


2 Answers

You should use

models.ForeignKey('self') 

as mentioned here.

like image 64
ohnoes Avatar answered Sep 23 '22 18:09

ohnoes


Yes, just do this:

class Example(models.Model):   parent_example = models.ForeignKey('self') 
like image 27
Joe Holloway Avatar answered Sep 19 '22 18:09

Joe Holloway