In Django, how do you make a model refer to itself?

I believe you can even exclude the app name which would look like:

ref_employee= models.ForeignKey('Employee',null=True,blank=True)

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

To create a recursive relationship -- an object that has a many-to-one relationship with itself -- use models.ForeignKey('self').

So you have it right. It's usually faster to determine if code will do what you want by running it :)


yes this is correct but consider you should write 'null=True' because if you don't mention that,in your database recursively create a joint table


You can reference other models by name (using a string, including package), instead of by the class directly:

So, if your Employee class is in the hr app:

class Employee(models.model):
   other_employee = models.ForeignKey('hr.models.Employee', null=True, blank=True)