FrameWork/Django
ORM
mansoorrr
2024. 7. 15. 21:30
ORM?
객체와 관계형 db를 연결해줌
ORM을 이용하면 쿼리를 적지 않고도 DML 수행 가능
객체지향적인 코드를 통해 데이터를 다루기 때문에 가독성이 높고, 생산성을 높여줌
[Django 기초명령어]
dir(me): 사용가능한 명령어들 보여줌
QuerySet API reference | Django documentation
The web framework for perfectionists with deadlines.
docs.djangoproject.com
[CRUD]
- 기본적으로 Django의 ORM은 <모델명>.objects.<query> 순으로 입력된다.
- 자주 사용되는 함수
번호 | 함수 | 내용 | 비고 |
1 | all() | 모든내용 반환 | 리스트로 반환 |
2 | get() | 특정조건 반환 | unique한 데이터만 반환 |
3 | filter() | 특정조건 반환 | 여러개 있으면 모두 반환 |
4 | creat() | 데이터 성생 | ()안에 모델에서 정의한 필드들 넣어줌 |
5 | delete() | 데이터 삭제 | 객체를 만들어 놓고 해당 객체에 delete() |
6 | count() | 데이터 갯수 반환 | null은 제외 |
7 | aggregate() | 집계 | - Sum, Count, Avg, Min, Max와 함께 사용됨 - aggregate(Count('id')) |
[QuerySets]
- 필터들을 동시에 쓸 수 있게 만들어줌
- 구체적으로 조건 입력될때만 데이터를 반환함(게으름)
[lookup]
- "_"를 통해 실시하는 함수
- 이어서 쓸 수 있음
번호 | 함수 | 내용 | 비고 |
1 | <필드>__gt | 크다 | |
2 | <필드>__gte | 같거나 크다 | |
3 | <필드>__lt | 작다 | |
4 | <필드>__lte | 같거나 작 | |
5 | <필드>__range | 특정범위 | |
6 | <필드>__contains | 문자열 포함 |
[ForeignKey Filter]
- foreignKey로 지정되어있는 필드에서 해당 문법을 통해 참조하고 있는 다른 모델의 정보를 끌어올 수 있음
- <modelA>.objects.filter(<modelA:Field1>__<modelB:Field3>)
- 모델A의 Field1은 modelB와 연결되어있음(FK)
- modelA의 Field1을 활용해 modelB의 Field3 정보를 가져옴
[related_name]
- ForeignKey, ManyToMany등에서 모두 사용 가능
- ForeignKey Filter처럼 데이터를 가져올 수 있지만 related_name 을 이용해 바로 가져올 수 있게 함
- 아래의 경우 Booking모델의 user필드는 ForeignKey로 User모델을 참조함
- 한명의 user가 예약한 부킹 정보를 알기 위해서는 다음과 같은 순서가 필요함
- user 정보 가져오기
- Booking.objects.filter(user==user)
- 하지만 저렇게 related_name을 걸어놓으면 단순해짐
- user정보 가져오기
- user.bookings
class Booking(CommonModel):
'''Booking Model Definition'''
class BookingKindChoice(models.TextChoices):
ROOM = ('room', 'Room')
EXPERIENCE = ('experience', 'Experience')
kind = models.CharField(max_length=20, choices=BookingKindChoice.choices,)
user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='bookings',)
room = models.ForeignKey('rooms.Room', on_delete=models.SET_NULL, null=True, blank=True, related_name='bookings',)
[Reverse Accessor]
- ForeignKey를 지정한 모델들에 대해서는 모델명_set을 통해 역으로 데이터를 받을 수 있다.
class Room:
user = models.ForeignKey('users.User', on_delete=....)
name = models.CharField(...)
category = models.ForeignKey('categories.Category', on_delete=...)
'''
user필드는 User모델을 참조하고 있기 때문에 user.room_set.all()을 통해 해당 user의 모든 room을 확인할 수 있다.
category필드는 Category모델을 참조하고 있기 때문에 category.room_set.all()을 통해 해당 category의 모든 room을 확인할 수 있다.
'''
class Category:
name = models.CharField(...)
user = models.ForeignKey('users.User', on_delete=....)
'''
user필드는 User모델을 참조하고 있기 때문에 user.category_set.all()을 통해 해당 user의 모든 category를 확인할 수 있다.
'''