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
'Computer Programming > AI' 카테고리의 다른 글
TIL_Django Project에서 회원 가입 페이지 (0) | 2023.09.11 |
---|---|
WIL_다섯 번째 주 (0) | 2023.09.09 |
Django Project에서 render와 redirect의 차이점 (0) | 2023.09.07 |
TIL_Django Project에서 DetailPage 만들기 (0) | 2023.09.06 |
TIL_Django Project에서 ORM(Object Relational Mapping) (0) | 2023.09.05 |