Django model recursive relationship

折月煮酒 提交于 2019-12-11 05:02:06

问题


  1. Why would I create a recursive relationship?
  2.     aField = models.ForeignKey('self')
    
  3. Is this the same with the above?
        class aClass(models.Model):  
        aField = models.ForeignKey('aClass')

回答1:


  1. You may need to create a recursive relationship when you would like to have parent and child nodes with identical model structure. For example if you have comments with text, data and user_id:

    class Comment( models.Model ):
        text = models.TextField()
        create_date_time = models.DateTimeField()
        parent_comment = models.ForeignKey( 'self' )
    
  2. I think yes (you can try to test it) but it's not a good form. If you change a class name then you must change the string value in brackets. If you use 'self' you haven't this headache.



来源:https://stackoverflow.com/questions/13182721/django-model-recursive-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!