django orm tutorial 3

dooh kim·2020년 9월 9일
0

queryset-tutorial

목록 보기
3/5

F() 옵션 사용법

Filters can reference fields on the model

Django provides F expressions to allow such comparisons. Instances of F() act as a reference to a model field within a query. These references can then be used in query filters to compare the values of two different fields on the same model instance.

같은 모델 인스턴스에서 다른 필드들의 값을 비교하기 위해 F()를 사용한다.

For example, to find a list of all blog entries that have had more comments than pingbacks, we construct an F() object to reference the pingback count, and use that F() object in the query:

entry field중 "number_of_comments" 와 "number_of_pingbacks" 값을 비교 할 것이다.

from django.db.models import F

# number_of_pingbacks 값보다 number_of_comments 
# 값이 큰 Entry 객체
Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks'))
# 두배보다 큰 Entry 객체
# __gt  ~보다 크다  |  __gte ~보다 크거나 같다  

Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks') * 2)

# 두개의 필드 값을 합친 것 보다 작은 Entry 객체(더하기 가능)
# __lt  ~보다 작다 | __lte ~보다 작거나 같다.

Entry.objects.filter(rating__lt=F('number_of_comments') + F('number_of_pingbacks'))


# 관계도 확장하여 authors name 과 blog name이 동일한 entry 객체
Entry.objects.filter(authors__name=F('blog__name'))


from datetime import timedelta

# pub_date 보다 3일 이후보다 큰 데이터 이후에 수정된 데이터 수집
Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))
profile
testify to the light

0개의 댓글