Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Assume we have class Employee. I want to have a field which references a different instance of the same class.

How to write this? How about the following code?

ref_employee= models.ForeignKey('self',null=True,blank=True) 
like image 738
user469652 Avatar asked Feb 06 '11 01:02

user469652


People also ask

What is def __ str __( self in Django?

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.

How do I create an instance of a Django model?

To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .

What is the purpose of __ Str__ method in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model. # Create your models here. This will display the objects as something always in the admin interface.

What is Self in Django?

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes.


2 Answers

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 :)

like image 75
Jonny Buchanan Avatar answered Sep 28 '22 18:09

Jonny Buchanan


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

ref_employee= models.ForeignKey('Employee',null=True,blank=True) 
like image 32
Stryker Avatar answered Sep 28 '22 20:09

Stryker