Home > Software design >  where puting ForeignKey in django?
where puting ForeignKey in django?

Time:06-24

one of the questions that came to my mind is that in a many-to-one relationship in Django, where should the foreign key be located? I mean, it should be in many or in part one?

For example, we have two classes, post and comment: in this case, where should the ForeignKey be located in the comment or post class?

post model :

class post(models.model):
    created_at = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.ManyToManyField("PostCategory", blank=True)
    caption = models.CharField(max_length=2000)

comment model :

class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, 
          verbose_name=_('user'), on_delete=models.CASCADE)
    text = models.TextField()
    

Now here is the comment field where the foreign key should be defined?

CodePudding user response:

Foreign key must be used on the "Many" side of the Many-to-one relationships.

In your question, you have Post and Comment models. Since each post can have many comments, you should put a foreign key into your Comment model.

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
  • Related