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

92๐Ÿ‘

โœ…

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 ๐Ÿ™‚

๐Ÿ‘คJonny Buchanan

5๐Ÿ‘

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

ref_employee= models.ForeignKey('Employee',null=True,blank=True)
๐Ÿ‘คStryker

4๐Ÿ‘

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)
๐Ÿ‘คnelhage

3๐Ÿ‘

Yes, this is correct but consider writing 'null=True' because if you donโ€™t mention that, your database recursively creates a joint table.

๐Ÿ‘คAMIN

0๐Ÿ‘

A constraint forcing id and ref_employee_id to have separate values is outside the scope of Djangoโ€™s ORM. You will need to add said constraint at the database level, via SQL in syncdb or manually.

Leave a comment