T.I.L May 18, 2023 (Django 역참조)
2023. 5. 18. 12:10ㆍT.I.L (Today_I_Learned)
역참조
외래 키(ForeignKey 또는 OneToOneField 또는 ManyToManyField)를 사용해 참조하는 object를 역으로 찾을 수 있습니다.
#기본 사용자 모델 예시
class User(AbstractBaseUser):
user_name = models.CharField(max_length=30, unique=True)
email = models.EmailField(max_length=255, unique=True)
#사용자 프로필 모델 예시
class UserProfile(models.Model):
# related_name은 역참조시 사용, 지정하지 않을시 '테이블명소문자_set'으로 역참조를 찾아갑니다.
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="USER", related_name="user_profile")
profile_image = models.ImageField("PROFILE IMAGE", default="default_profile_pic.jpg", upload_to="profile_pics", blank=True)
nickname = models.CharField("NICKNAME", max_length=10, null=True, unique=True, error_messages={"unique": "이미 사용 중이거나 탈퇴한 사용자의 닉네임입니다!"})
age = models.IntegerField("AGE", null=True)
introduction = models.TextField(null=True, default="안녕하세요!")
UserProfile 모델이 User 모델을 OneToOneField로 정참조를 하고 있습니다.
반대로 User 모델은 UserProfile 모델을 역참조 할 수 있습니다.
역참조하여 데이터 출력해보기
외래키 related_name 옵션
- 왜래 키 지정 시 related_name 옵션을 사용한 경우 역참조 시 사용될 이름을 지정할 수 있습니다.
# 역참조 테스트1
class Test(APIView):
def get(self, request):
# UserProfile 모델은 외래키 지정시 related_name 옵션으로 user_profile을 지정해 줬음.
introduction = request.user.user_profile.introduction
# User 모델이 역참조를 할 때 user_profile이라는 related_name 옵션을 사용했음.
return Response(introduction, status=status.HTTP_200_OK)
# 결과
"안녕하세요!"
'T.I.L (Today_I_Learned)' 카테고리의 다른 글
T.I.L May 22, 2023 (TMDB API) (0) | 2023.05.22 |
---|---|
T.I.L May 19, 2023 (Django CORS policy 문제) (0) | 2023.05.19 |
T.I.L May 17, 2023 (DRF 모델간 관계(참조)에 관해 겪던 문제 해결) (0) | 2023.05.17 |
T.I.L May 15, 2023 (DRF 팀 프로젝트 피드백) (0) | 2023.05.15 |
T.I.L May 12, 2023 (DRF 팀 프로젝트 중 모델들의 관계에 대해 어려움을 겪고 있습니다.) (0) | 2023.05.15 |