자주 사용되는 메서드 위주로 설명합니다. 상세 내용은 Django의 QuerySet API reference를 참고해주세요.
QuerySet API reference | Django documentation | Django
sample data를 가지고 설명드리도록 하겠습니다.
from django.db import models
class Notice(models.Model):
title = models.CharField(max_length=100)
likeCount = models.IntegerField()
viewCount = models.IntegerField()
contents = models.TextField()
def __str__(self):
return f'제목 : {self.title}, 좋아요 수 : {self.likeCount}, 조회수 : {self.viewCount}'
보기 쉽게 전체 데이터를 엑셀로 옮겨보았습니다. 현재 data입니다.
ORM이란 우리가 만든 모델 클래스와 DB에 생성된 테이블을 자동으로 연관지어 주는 기술로 우리가 DB를 직접 조작할 필요 없이 모델 클래스의 python 문법을 통해서 DB를 조작할 수 있는 편리한 기술입니다.
# python manage.py shell
all, filter, exclude, get, count, first, last, exists(데이터의 유무, True, False로 반환), order_by(정렬), reverse 등이 있습니다.
다중데이터를 처리하기 위해 union, intersection, difference를 사용하기도 합니다.
all
모든 요소에 접근할 때 사용합니다.
>>> from main.models import Notice
>>> Notice.objects.all()
<QuerySet [<Notice: 제목 : test title 1, 좋아요 수 : 1, 조회수 : 2>, <Notic
e: 제목 : test title 2, 좋아요 수 : 2, 조회수 : 4>, <Notice: 제목 : test ti
tle 3, 좋아요 수 : 3, 조회수 : 6>, <Notice: 제목 : test title 4, 좋아요 수
: 4, 조회수 : 8>, <Notice: 제목 : test title 5, 좋아요 수 : 5, 조회수 : 10>
]>
>>> Notice.objects.all().order_by('-pk')
<QuerySet [<Notice: 제목 : test title 5, 좋아요 수 : 5, 조회수 : 10>, <Noti
ce: 제목 : test title 4, 좋아요 수 : 4, 조회수 : 8>, <Notice: 제목 : test t
itle 3, 좋아요 수 : 3, 조회수 : 6>, <Notice: 제목 : test title 2, 좋아요 수
: 2, 조회수 : 4>, <Notice: 제목 : test title 1, 좋아요 수 : 1, 조회수 : 2>
]>
>>> Notice.objects.all().count()
5
get
특정 요소를 정확히 알고 있을 때 사용합니다. 요소에 접근할 때에는 점을 사용합니다.
>>> q = Notice.objects.get(id=1)
>>> q
<Notice: 제목 : test title 1, 좋아요 수 : 1, 조회수 : 2>
>>> q = Notice.objects.get(pk=1)
>>> q
<Notice: 제목 : test title 1, 좋아요 수 : 1, 조회수 : 2>
>>> q.id
1
>>> q.title
'test title 1'
>>> q.viewCount
2
filter
, exclude
위 매서드는 이어 붙여 사용할 수 있습니다. filter().exclude().filter().exclude() 처럼요. filter는 조건에 맞는 값을 반환하고, exclude는 조건에 맞지 않는 값을 반환합니다.
연산자를 붙일 때에는 __(언더바 2개)를 붙입니다. 연산자의 종류는 contains(포함), in(다중 조건 포함), exact, iexact, gt(>), lt(<), gte(>=), lte(<=), startswith(앞에 매칭), endswith(뒤에 매칭), range(범위), date, year, month, day, week, week_day, quarter, time, hour, minute, second, regex 등이 있습니다.
get은 filter로도 잡아낼 수 있습니다.
>>> Notice.objects.filter(title='test')
<QuerySet []>
>>> Notice.objects.filter(title='test title 1')
<QuerySet [<Notice: 제목 : test title 1, 좋아요 수 : 1, 조회수 : 2>]>
>>> Notice.objects.filter(id=1)
<QuerySet [<Notice: 제목 : test title 1, 좋아요 수 : 1, 조회수 : 2>]>
>>> Notice.objects.filter(viewCount=4)
<QuerySet [<Notice: 제목 : test title 2, 좋아요 수 : 2, 조회수 : 4>]>
>>> Notice.objects.filter(title__contains='test')
<QuerySet [<Notice: 제목 : test title 1, 좋아요 수 : 1, 조회수 : 2>, <Notic
e: 제목 : test title 2, 좋아요 수 : 2, 조회수 : 4>, <Notice: 제목 : test ti
tle 3, 좋아요 수 : 3, 조회수 : 6>, <Notice: 제목 : test title 4, 좋아요 수
: 4, 조회수 : 8>, <Notice: 제목 : test title 5, 좋아요 수 : 5, 조회수 : 10>
]>
좀 더 세부적으로 filter는 아래 문법을 따릅니다.
>>> Notice.objects.filter(title='test title 1')
<QuerySet [<Notice: 제목 : test title 1, 좋아요 수 : 1, 조회수 : 2>]>
>>> Notice.objects.filter(likeCount__lt=3)
<QuerySet [<Notice: 제목 : test title 1, 좋아요 수 : 1, 조회수 : 2>, <Notic
e: 제목 : test title 2, 좋아요 수 : 2, 조회수 : 4>]>
>>> Notice.objects.filter(likeCount__gt=3)
<QuerySet [<Notice: 제목 : test title 4, 좋아요 수 : 4, 조회수 : 8>, <Notic
e: 제목 : test title 5, 좋아요 수 : 5, 조회수 : 10>]>
# Notice.objects.filter([필드명]=value)
# Notice.objects.filter([필드명]__[조건]=value)
>>> q = Notice.objects.create(title='sample', likeCount=100, viewCount=100,
contents='hello world')
>>> q
<Notice: 제목 : sample, 좋아요 수 : 100, 조회수 : 100>
>>> q.save()