In Django, how do you make a model refer to itself?
Assume we have class Employee
. I want to have a fie开发者_运维问答ld 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)
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)
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)
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
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.
精彩评论