본문 바로가기
Languages/Python

[Django] ORM, QuerySets - Djangogirls

by 김크롱 2020. 7. 30.

QuerySets

 : 전달받은 모델의 객체 목록

 

 

Django Interactive Console 접속

cmd

(myvenv) ~/djangogirls$ python manage.py shell

 

 

 

모든 객체 조회

cmd

>>>from blog.models import Post

>>>Post.objects.all()

 

post가 없는 상태

 

객체 생성

 - 글 추가하기

 

cmd

>>> Post.objects.create(author=me, title='Sample title', text='Test')

>>> from django.contrib.auth.models import User

>>> User.objects.all()

<QuerySet [<User: name>]>

>>> me = User.objects.get(username='name')

>>> Post.objects.create(author=me, title='Sample title', text='Test')

>>> Post.objects.all()

<QuerySet [<Post: Sample title>]>

 

 

 

필터링

 - .filter()

 

전체 포스터

>>> Post.objects.all()

 

작성자가 나인 경우

>>> Post.objects.filter(author=me)

 

제목이 title인 경우

>>> Post.objects.filter(title__contains='title'

 

 

 

게시글 목록

 - 게시일(published_date)로 과거 작성한 글을 필터링함

 

cmd

>>> from django.utils import timezone

>>> Post.objects.filter(published_date__lte=timezone.now())

 

추가한 게시물이 없는 상태

>>> post = Post.objects.get(title="Sample title")

>>> post.publish()

>>> Post.objects.filter(published_date__lte=timezone.now())

[<Post: Sample title>]

 

게시물이 추가됨

 

 

정렬

 - QuerySets는 객체목록을 정렬할 수 있음.

 

cmd

오름차순

>>> Post.objects.order_by('created_date')

 

 

 

내림차순

 : -만 붙여주면 됨

>>> Post.objects.order_by('-created_date')

 

 

 

쿼리셋 연결

>>> Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')

 

 

 

 

 

 

https://tutorial.djangogirls.org/ko/django_orm/

 

Django ORM(Querysets) · HonKit

이번 장에서는 장고를 데이터베이스에 연결, 데이터를 저장하는 방법에 대해서 알아볼 거에요. 함께 시작해봅시다! 핵심만 말하자면, 쿼리셋(QuerySet)은 전달받은 모델의 객체 목록입니다. 쿼리��

tutorial.djangogirls.org