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

前端 未结 4 1981
耶瑟儿~
耶瑟儿~ 2020-12-15 15:49

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 followi

相关标签:
4条回答
  • 2020-12-15 16:18

    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)
    
    0 讨论(0)
  • 2020-12-15 16:22

    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.

    0 讨论(0)
  • 2020-12-15 16:36

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

    ref_employee= models.ForeignKey('Employee',null=True,blank=True)
    
    0 讨论(0)
  • 2020-12-15 16:37

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

    0 讨论(0)
提交回复
热议问题