Traian
Traian

Reputation: 3003

Django model recursive relationship

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

Upvotes: 2

Views: 5087

Answers (1)

sergzach
sergzach

Reputation: 6764

  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.

Upvotes: 7

Related Questions