Computer Programming/AI

TIL_Django Project에서 related_name이란

JYCoder 2023. 9. 8. 18:38

models.py에서 class와 attributes가 정의되어 있다.

class Todo(models.Model):
    content = models.TextField()
    is_done = models.BooleanField(default=False)


class Comment(models.Model):
    todo = models.ForeignKey(Todo, on_delete=models.CASCADE)
    content = models.TextField()

 

한 개의 Todo Object는 여러 개의 Comment Object들을 가질 수 있다. 

 

todo1 = Todo.objects.get(id =1)
todo1.comment.all() #Error

todo1 object 안에는 comment라는 attribute이 없었기 때문에 위와 같이 todo1.comment.all()을 실행했을 때 에러가 난다.

 

이러한 상황을 역참조를 한다고 하는데, [Classname]_set을 사용하면 가능하다.

todo1 = Todo.objects.get(id =1)
comments = todo1.comment_set.all()

이 때, comment_set 대신에 related_name을 사용해도 가능하다.

 

따라서, related_name이란 class를 정의할 때, 정참조 하고 있는 class의 instance에서 거꾸로 참조 할 때 부를 이름인 것이다.

class Todo(models.Model):
    content = models.TextField()
    is_done = models.BooleanField(default=False)


class Comment(models.Model):
    todo = models.ForeignKey(Todo, on_delete=models.CASCADE, related_name = 'all_comments')
    content = models.TextField()

위와 같이 related_name을 정의 해 주면 아래의 코드가 문제 없이 정보를 가져올 수 있다.

todo1 = Todo.objects.get(id =1)
comments = todo1.all_comments.all()

 

LIST