lution88

[Django] _set 의 사용 (역참조) 본문

개발일지/# Django

[Django] _set 의 사용 (역참조)

lution88 2022. 3. 27. 17:10

집과 사람이라는 모델이 있다고 가정한다.

 

집 model 은 살고있는 사람, 방의 개수와 같은 정보가 있다.
그 중 사람 column 은 사람 모델을 Foreign Key 로 지정한 값이다.
사람 model 은 이름, 나이와 같은 정보를 가지고 있다.

위와 같은 모델이 존재할 때,
참조
집 모델에서 사람(Foreign Key)를 불러 들이는 것을 "참조" 라 한다.

역참조
위와 반대로 사람모델집 모델을 불러들일 때를 "역참조" 라고 한다.

 

역 참조를 사용하는 방법

1. _set manager 를 사용하는 방법.
 사람.집_set.all( )  -> (참조되고 있는 모델(사람).참조하는 모델(집)_set.all( )

역참조 코드.

 

class Room(models.Model):
    host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
    name = models.CharField(max_length=200)
    description = models.TextField(null=True, blank=True)
    participants = models.ManyToManyField(User, related_name='participants', blank=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-updated','-created']
    
    def __str__(self):
        return self.name

class Message(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    body = models.TextField()
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-updated','-created']
    
    def __str__(self):
        return self.body[0:50]

위와 같이 Room 모델과 Message 모델이 있을 때.

room_messages = room.message_set.all( )

room_messages = 참조되고 있는 모델(room).참조하는모델(message)_set.all()

즉, room 모델이 message 모델을 역참조 하여 room_messages 에 담는 상황.

Comments