Notice
Recent Posts
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- Wil
- Model
- 스파르타코딩클럽후기
- error
- 코딩교육
- vscode
- git
- 장고
- 선형회귀
- 내일배움캠프
- 터미널
- MySQL
- 머신러닝
- 스파르타코딩클럽
- network
- 디스코드봇
- musicbot
- 기초문법
- Python
- 파이썬
- 웹프로그래밍A-Z기초
- orm
- 페이지네이션
- predict
- JavaScript
- Django
- HTML
- paginator
- cs
- 파이널프로젝트
- Today
- Total
lution88
[Django] _set 의 사용 (역참조) 본문
집과 사람이라는 모델이 있다고 가정한다.
집 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 에 담는 상황.
'개발일지 > # Django' 카테고리의 다른 글
[Django] Model 이해하기! (0) | 2022.04.20 |
---|---|
[Django] 폼을 간단하게, Model Form (0) | 2022.04.07 |
[TIL] 카테고리 검색기능 만들기 (0) | 2022.03.25 |
[TIL] Django-Paginator 기능구현 (0) | 2022.03.07 |
[TIL] Django 템플릿 언어 글자수 제한 (0) | 2022.03.07 |
Comments