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)
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.
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() .
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.
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.
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 :)
I believe you can even exclude the app name which would look like:
ref_employee= models.ForeignKey('Employee',null=True,blank=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With