쿼리셋은 DB로 부터 전달받은 모델의 객체 목록

장고 쉘에서 쿼리셋을 사용할 수 있음

 

● 장고 쉘 켜기

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

→ 결과 : 인터렉티브 콘솔(장고쉘)이 켜짐

(InteractiveConsole)
>>>

 

● all : 객체 전체 조회

>>> from notice.models import Notice, Reply 		# 장고 쉘로 모델 import

>>> Notice.objects.all()
<QuerySet [<Notice: 알려드립니다.>, <Notice: 이용 안내>]>

 

● create(key = value) : 객체 생성

>>> from django.contrib.auth.models import User
>>> me = User.objects.get(username='master')

>>> Notice.objects.create(writer=me, title='점검 안내', content='내일 점검합니다.')

 

● filter(key = value) : 필터링

>>> Notice.objects.filter(writer=me)
[<Notice: 점검 안내>]

 

● order_by('속성') : 정렬

>>> Notice.objects.order_by('title')			# 오름차순
[<Notice: 알려드립니다.>, <Notice: 이용 안내>, <Notice: 점검 안내>]

>>> Notice.objects.order_by('-title')			# 내림차순
[<Notice: 점검 안내>, <Notice: 이용 안내>, <Notice: 알려드립니다.>]


>>> Notice.objects.order_by('user__first_name')		# User 모델의 first_name 컬럼 오름차순

▷ 관계를 갖은 다른 모델의 컬럼에 접근할 때는 더블 언더스코어(__, 던더)를 사용함 (lookups across relationships)

 

● get(key = 'value') : 단일행 가져오기

 - 결과 행이 여러개일 시 오류발생, where절 역할

 

● values(['속성']) :  value 가져오기

 - dictioinary 형태로 반환

>>> Blog.objects.values()			# 전체 속성
<QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>

>>> Blog.objects.values('id', 'name')			# 일부 속성
<QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>

 - 모델객체를 가져온 후 내부의 값을 확인하고 싶을 때 사용해도 됨

>>> Notice.objects.get(id=2)
<Notice : Notice object (2)>

>>> Notice.objects.get(id=2).values()
<Queryset [{'id':2, 'writer':'master', 'title':'공지', 'content':'점검예정입니다.'}]>

 

# get과 filter 사용시 value 가져올 때의 차이점

>>> Profile.objects.get(user=user.id)
Profile object (1)
>>> Profile.objects.get(user=user.id).point
12.0


>>> Profile.objects.filter(user=user.id)
<QuerySet [<Profile: Profile object (1)>]>
>>> Profile.objects.filter(user=user.id).values('point')
12.0

→ get()의 경우 1개만 가져오는 것이기 때문에 바로 컬럼으로 접근가능

→ filter()의 경우 여러개를 가져오는 것이라 QuerySet 자료형임. values()를 사용하여 컬럼으로 접근해야 함

 

 

exclude([key = 'value']) : 배제하고 가져오기

>>> Notice.objects.exclude(title='')		# title이 공백인 자료는 제외하고 가져오기

 

● distinct('속성') : 중복제거하고 가져오기

>>> Notice.objects.distinct('content')		# content 중복 제거하고 가져오기

 

● annotate() : 별칭 지정

from django.db.models import Count

>>> Notice.objects.annotate(total=Count('id'))		# id의 갯수를 total로 명명

→ total이라는 칼럼을 새로 만들었다고 생각

 

조건 키워드 : get(), filter() 사용시, and로 결합

키워드 설명 example
__lt / __gt
(litter / greater)
~보다 작다 / ~보다 크다 id>3 검색
>> Notice.objects.filter(id__gt = 3)
__lte / __gte ~보다 같거나 작다 / ~보다 같거나 크다  
__in 포함 (= or) id가 2, 3 검색
>> Notice.objects.filter(id__in = [2, 3])
__year / __month / __day 해당 년도, 월, 일 검색 >> Notice.objects.filter(pub_date=2020)
__isnull null인지 >> Notice.objects.filter(file__isnull=True)
__contaions / __icontains 포함하는지 (icontains는 대소문자 구분 X) 내용에 '고객'이 포함되는 것 검색
>> Notice.objects.filter(content__contains='고객')
__startswith / __istartswith 시작문자열 (istartswith는 대소문자 구분 X)  
__endswith / __iendswith 끝문자열 (iendswith는 대소문자 구분 X)  
__range 범위 (= between) id가 2~8 검색
>> Notice.objects.filter(id__range = (2, 9))

'Framework > Django' 카테고리의 다른 글

select_related, prefetch_related  (0) 2021.01.06
ForeignKey, OneToOneField, ManyToManyField  (0) 2020.12.23
사용자 정보 가져오기(user)  (0) 2020.12.14
Django Form(장고 폼)  (0) 2020.12.10
MTV 패턴 - Template  (0) 2020.12.09

+ Recent posts