user6089877
user6089877

Reputation:

Django model foreign key in the same table

Before to send this kind of modification to my database, I just would like to know if what I do is OK or not.

class Comments(models.Model):
    text = models.CharField(max_length=300, null=False)
    image = models.FileField(upload_to=user_directory_path_comments, validators=[validate_file_extension], blank=True, null=True)
    articles = models.ForeignKey(Articles, verbose_name="Article", null=False)
    author = models.ForeignKey(User, verbose_name="Auteur")
    in_answer_to = models.ForeignKey(Comments, verbose_name="En réponse au commentaire", blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création")
    update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification")

    def __str__(self):
        return self.text

I have a model called Comments for listing the comments in my article's blog. I want to add the functionality to answer to a comment and so I add a field name where, if it's an answer, I add the ID of the comment.

So, is it OK if I add a foreign key field, knowing that it's is about the same table ? This is not really a foreign key ?

Upvotes: 10

Views: 7258

Answers (1)

Chris
Chris

Reputation: 137228

You can have a ForeignKey that references the same model, but in that case you should use 'self' as the othermodel argument.

From the documentation:

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

Upvotes: 19

Related Questions