Django의 ORM
ORM ?
ORM(Object-Relation Mapping)이란, 객체(Object)
와 관계형 데이터베이스(Relational)
을 연결(Mapping)해 주는것을 의미한다. 간단하게 설명하면, 데이터베이스의 테이블을 객체(Object)와 연결하여 테이블에 CRUD
할 때, SQL 쿼리를 사용하지 않고 가능하도록 함.
1️⃣ 데이터 생성(Create)
# Post는 블로그 앱에서 만든 포스트 모델이라고 가정
# def __str__(self)로 해당 모델의 타이틀이 반환이 될 것임
Post.objects.create(author=admin, title='This is a test title', content='test content')
# 결과 : <Post: This is a test title>
2️⃣ 데이터 조회(Read)
Post.objects.all()
# 결과 : <QuerySet [<Post: This is a test title>]>
3️⃣ 데이터 업데이트(Update)
# 해당 제목에 Post 모델을 불러온다.
# SELECT title From blog_post WHERE title = 'This is a test title'; 느낌?
post = Post.objects.get(title='This is a test title')
post.title = 'This is a test title2'
# 변경된 내용을 테이블에 반영
post.save()
다른 방법으로 테이블 조회
Post.objects.get(title__contains='title2')
# or
Post.objects.filter(title__contains='title2')
4️⃣ 데이터 삭제(Delete)
post = Post.object.get(title__contains='title2')
post.delete()
조회조건 🔽
조회 조건 | 설명 | 사용 방법 |
---|---|---|
__contains | 지정한 문자열을 포함하는 데이터 조회 | Post.objects.filter(title__contains=’test’) |
__icontains | 지정한 문자열의 대소문자 구분없이 포함하는 데이터 조회 | Post.objects.filter(title__icontains=’this’) |
__lt | 값이 작은 경우(lt: less than) | Post.objects.filter(published_at__lt=timezone.now()) |
__lte | 값이 작거나 같은 경우(lte: less than or equal) | Post.objects.filter(published_at__lt=timezone.now()) |
__gt | 값이 큰 경우(gt: greater than) | Post.objects.filter(published_at__gt=timezone.now()) |
__gte | 값이 크거나 같은 경우(gt: greater than or equal) | Post.objects.filter(published_at__gte=timezone.now()) |
__in | 주어진 리스트에 포함되는 데이터 조회 | Post.objects.filter(id__in=[1, 2, 3]) |
__year | 해당 년도 조회 | Post.objects.filter(created_at__year=’2019’) |
__year | 해당 월로 조회 | Post.objects.filter(created_at__month=’5’) |
__day | 해당 일로 조회 | Post.objects.filter(created_at__day=’21’) |
__isnull | 해당 열이 null인 데이터 조회 | Post.objects.filter(published_at__isnull=True) |
__startswith | 해당 문자열로 시작하는 데이터 조회 | Post.objects.filter(title__startswith=’This’) |
__istartswith | 대소문자를 가리지 않고 해당 문자열로 시작하는 데이터 조회 | Post.objects.filter(title__istartswith=’this’) |
__endswith | 해당 문자열로 끝나는 데이터 조회 | Post.objects.filter(title__endswith=’title’) |
__iendswith | 대소문자를 가리지 않고 해당 문자열로 끝나는 데이터 조회 | Post.objects.filter(title__iendswith=’title’) |
__range | 범위를 지정하여 조회(sql의 between) | Post.objects.filter(id__range=(1, 10)) |
- 제외 조건 : 특정 조건을 제외한 데이터를 조회 가능
Post.objects.all().exclude(title__contains='This')
- 여러 조건으로 조회 : 여러 조건을 걸어 데이터를 조회
Post.objects.filter(title__contains='this', title__endswith='title')
# this를 포함하는 제목의 Post 모델들로 필터를 하고 또 거기서 title을 포함하고 있는 Post 모델로 분리
Post.objects.filter(title__contains='this').filter(title__endswith='title')
# this를 포함하는 여러개의 Post들을 슬라이싱
Post.objects.filter(title__contains='this')[:2]
정렬 🔽
아래와 같이 조회할 데이터를 오름차순 또는 내림차순으로 정렬할 수 있음
- 오름차순 : Post.objects.order_by(‘created_at’)
- 내림차순 : Post.objects.order_by(‘-created_at’)
댓글남기기