Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to link a Django model field to an instance of the same model

Tags:

key

django

models

I'm trying to design a Django model for articles with attributes like title, publication date, etc. One of the attributes is other article(s) that the article in question is commenting on. I'm not sure how to code this since there is no foreign key involved - I just want a reference to other instances of the Article model (i.e. one or more other articles). This is what I have so far:

class Article(models.Model):
    title = models.CharField(max_length=400)
    publication_date = date_published = models.DateField()
    comment_on = ?????????????

Any suggestions would be much appreciated. Thank you!

like image 590
henrich Avatar asked Nov 01 '25 22:11

henrich


1 Answers

I think you should user ForeignKey

 comment_on = models.ForeignKey('self',null=True,blank=True)

To create a recursive relationship -- an object that has a many-to-one relationship with itself -- use models.ForeignKey('self').

Django foreign key docs

like image 183
Alexander Sysoev Avatar answered Nov 03 '25 13:11

Alexander Sysoev