Django에서 related_name을 사용하는 경우데 대해 알아보자
1:N 관계에서 N에서 1을 바라보는 column이 여러개일 때,
1에서 N을 역참조할때, 어떤 column을 기준으로 역참조해야할지 알 수 없다.
예시)
airport_table(1), path_table(N)
하기와 같이 models.py
를 작성하면, SystemCheckError
가 발생한다.
# models.py
from django.db import models
class Airport(models.Model):
name = models.CharField(max_length=45)
class Meta:
db_table = 'airports'
class Path(models.Model):
airline = models.CharField(max_length=45)
departure = models.ForeignKey('Airport', on_delete=models.CASCADE)
destination = models.ForeignKey('Airport', on_delete=models.CASCADE)
class Meta:
db_table = 'paths'
이는 airport를 가지고 있는 Path를 역참조 할 때, Path의 해당 airport
를 destination
로 가지고 있는 Path를 찾아야할지, destination
으로 가지고 있는 Path를 찾아야할지 모르기 때문이다.
(기존에 역참조 manager 호출 매소드였던, airport.paths_set
으로는 구분 불가능)
이때 사용하는 것이 related_name 이다.
departure = models.ForeignKey('Airport', on_delete=models.CASCADE, related_name="path_departure")
destination = models.ForeignKey('Airport', on_delete=models.CASCADE, related_name="path_destination")
위와 같이 related_name
을 추가하면,
특정 airport를 departure로 가지고 있는 path를 찾을때는 airport.path_departure
를 이용하고,
특정 airport를 destination으로 가지고 있는 path를 찾을때는 airport.path_destination
을 이용하면 된다.