[230203 - TIL] Django - Making queries

Dongwoo Kim·2023년 2월 3일
0

TIL / WIL

목록 보기
75/113

1. F expressions

https://docs.djangoproject.com/en/4.1/ref/models/expressions/#f-expressions

모델 필드의 값, 모델 필드의 변환된 값 또는 주석이 달린 열을 나타냄

reporter = Reporters.objects.filter(name='Tintin')
reporter.update(stories_filed=F('stories_filed') + 1)

2. Limiting QuerySets

https://docs.djangoproject.com/en/4.1/topics/db/queries/#limiting-querysets

Python의 배열 슬라이싱 구문의 하위 집합을 사용하여 [QuerySet]특정 수의 결과로 제한합니다. 이것은 SQL의 LIMIT및 OFFSET절과 동일합니다.

  • LIMIT 5
    Entry.objects.all()[:5]
  • OFFSET 5 LIMIT 5
    Entry.objects.all()[5:10]
  • 네거티브 인덱싱(예: Entry.objects.all()[-1])은 지원되지 않습니다.
  • 슬라이스된 쿼리 세트의 추가 필터링 또는 정렬은 작동 방식의 모호한 특성으로 인해 금지됩니다.
  • 목록(예: SELECT foo FROM bar LIMIT 1Entry)이 아닌 단일 개체 를 검색하려면 슬라이스 대신 인덱스를 사용합니다. 예를 들어 다음 은 헤드라인의 알파벳순으로 항목을 정렬한 후 데이터베이스에서 첫 번째 항목을 반환합니다.
    Entry.objects.order_by('headline')[0] # *- **IndexError**발생
    Entry.objects.order_by('headline')[0:1].get() # - DoesNotExist 발생*

3. Field lookups

https://docs.djangoproject.com/en/4.1/topics/db/queries/#field-lookups

field__lookuptype=value

Python : Entry.objects.filter(pub_date__lte='2006-01-01')
	↓
 SQL   : SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
  • exact : "정확한" 일치
    조회 유형을 제공하지 않는 경우(즉, 키워드 인수에 이중 밑줄이 포함되지 않은 경우) 조회 유형은 exact로 간주됩니다
Entry.objects.get(headline__exact="Cat bites dog")
    	↓
SELECT ... WHERE headline = 'Cat bites dog';

Blog.objects.get(id__exact=14)  # Explicit form
Blog.objects.get(id=14)         # __exact is implied
  • iexact : 대소문자를 구분하지 않는 일치
Blog.objects.get(name__iexact="beatles blog")

# "Beatles Blog" "beatles blog" "BeAtlES blOG"
  • contains / icontains : 대소문자를 구분하는 / 구분안하는 포함 일치
Entry.objects.get(headline__contains='Lennon')
    	↓
SELECT ... WHERE headline LIKE '%Lennon%';
  • startswith / endswith / istartswith / iendswith

4. Lookups that span relationships

https://docs.djangoproject.com/en/4.1/topics/db/queries/#lookups-that-span-relationships

Entry.objects.filter(blog__name='Beatles Blog')
Blog.objects.filter(entry__headline__contains='Lennon')
  • (관련 Author모델이 있는 경우) author 항목과 연관된 name항목이 없으면 author가 누락되어 오류가 발생하는 것이 아니라 연결된 항목도 없는 것처럼 처리됩니다.
Blog.objects.filter(entry__authors__name='Lennon')
  • .author에 대한 name이 비어 있고 entryauthor가 비어 있는 blog객체를 반환합니다.
Blog.objects.filter(entry__authors__name__isnull=True)
  • 전자의 경우가 싫으면
Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)

5. Q objects

https://docs.djangoproject.com/en/4.1/topics/db/queries/#complex-lookups-with-q-objects

from django.db.models import Q
Q(question__startswith='Who') | Q(question__startswith='What')
	↓
WHERE question LIKE 'Who%' OR question LIKE 'What%'
Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
	↓
SELECT * from polls WHERE question LIKE 'Who%'
    AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
  • .Q조회 함수는 개체와 키워드 인수 를 혼합하여 사용할 수 있습니다 . 조회 함수에 제공된 모든 인수(키워드 인수 또는 Q 객체)는 함께 "AND"됩니다. 그러나 Q개체가 제공되는 경우 모든 키워드 인수의 정의보다 선행해야 합니다.
Poll.objects.get(
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
        question__startswith='Who',
    )

# INVALID QUERY
Poll.objects.get(
        question__startswith='Who',
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
    )


참고

profile
kimphysicsman

0개의 댓글