쿼리셋이란?
쿼리셋(QuerySet)은 전달받은 모델의 객체 목록이다. 쿼리셋은 데이터베이스로부터 데이터를 읽고, 필터를 걸거나 정렬 할 수 있다.
장고 쉘(shell)
로컬 콘솔에서 아래 명령을 입력한다.
x(myvenv) ~/djangogirls$ python manage.py shell
그러면 장고 인터랙티브 콘솔로 들어갈 수 있다.
모든 객체 조회하기
모든 글들을 출력하기 위해서 blog.models에서 Post 모델을 import 해온다.
>>> from blog.models import Post그리고 아래 명령을 입력해 모든 글들을 출력한다.
xxxxxxxxxx>>> Post.objects.all()<QuerySet [<Post: my post title>, <Post: another post title>]>
객체 생성하기
이번에는 새 글을 포스팅 해본다.
우선 작성자 정보를 가져오기 위해서 User 모델을 불러온다.
xxxxxxxxxx>>> from django.contrib.auth.models import User
객체를 조회할 때의 명령어를 User에 써서 모든 유저 정보를 알아보면
xxxxxxxxxx>>> User.objects.all()<QuerySet [<User: admin>]>
슈퍼유저 정보로 등록한 사용자가 표시된다. 이제 이 사용자의 인스턴스 정보를 가져온다.
xxxxxxxxxx>>> me = User.objects.get(username='admin')
me 변수에 사용자 이름이 'admin'인 User 인스턴스를 받아왔다.
이제 아래 명령을 통해 게시물을 만든다.
xxxxxxxxxx>>> Post.objects.create(author=me, title='Sample title', text='Test')
제대로 적용했는지 확인해보기 위해서 객체를 조회해보면 목록에 게시글이 하나 늘었다는 것을 볼 수 있다.
xxxxxxxxxx>>> Post.objects.all()<QuerySet [<Post: my post title>, <Post: another post title>, <Post: Sample title>]>
필터링하기
쿼리셋에서 중요한 기능은 데이터들을 필터링 하는 것이다. 예를 들어, 특정 사용자가 작성한 글 목록을 보고 싶은 경우에는 Post.objects.all()에서 all 대신, filter를 사용한다. 지금 같은 경우에는 작성자가 me인 조건을 넣으면 아래와 같이 된다.
xxxxxxxxxx>>> Post.objects.filter(author=me)[<Post: Sample title>, <Post: Post number 2>, <Post: My 3rd post!>, <Post: 4th title of post>]
제목에 'title'이라는 글자가 포함된 글들을 보고 싶다면 아래와 같이 하면 된다.
xxxxxxxxxx>>> Post.objects.filter(title__contains='title')[<Post: Sample title>, <Post: 4th title of post>]
장고의 timezone을 불러와서 과거에 작성한 글들을 필터링 하는 것도 가능하다.
xxxxxxxxxx>>> from django.utils import timezone>>> Post.objects.filter(published_date__lte=timezone.now())[]
지금 콘솔에서 추가한 게시물은 보이지 않지만 바꿀 수 있다. 먼저 게시하려는 게시물의 인스터스를 받아온다.
xxxxxxxxxx>>> post = Post.objects.get(title="Sample title")
그리고 publish 메소드를 사용해서 글을 게시한다.
xxxxxxxxxx>>> post.publish()
다시 게시글 목록을 가져오면 Sample title 게시글이 추가된 것을 볼 수 있다.
xxxxxxxxxx>>> Post.objects.filter(published_date__lte=timezone.now())[<Post: Sample title>]
정렬하기
쿼리셋은 객체 목록을 정렬할 수 있다. created_date 필드를 정렬해본다.
xxxxxxxxxx>>> Post.objects.order_by('created_date')[<Post: Sample title>, <Post: Post number 2>, <Post: My 3rd post!>, <Post: 4th title of post>]
쿼리셋 연결하기
이 쿼리셋들을 연결(chaining) 할 수 있다.
xxxxxxxxxx>>> Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
'Python > Django' 카테고리의 다른 글
| 장고 걸즈 튜토리얼 따라하기 10 - 장고 템플릿 (0) | 2019.01.02 |
|---|---|
| 장고 걸즈 튜토리얼 따라하기 9 - 템플릿 동적 데이터 (0) | 2018.12.27 |
| 장고 걸즈 튜토리얼 따라하기 7 - 장고 뷰 (0) | 2018.12.26 |
| 장고 걸즈 튜토리얼 따라하기 6 - 장고 urls (0) | 2018.12.24 |
| 장고 걸즈 튜토리얼 따라하기 5 - 배포 (0) | 2018.12.23 |