본문 바로가기
개발일지/Python

Python - filter에 or조건과 and 조건(python식 sql)

by 개발에정착하고싶다 2022. 11. 27.
320x100

부분적으로는 분명 아는 개념들인데, 이것들이 하나가 되었을때 비로소 힘을 발하는 구조에 대해서

이런 구조는 못본 것 같다.

 

거두절미하고

#1 or 조건

from django.db.models import Q
Book.objects.filter(Q(rating__lt=3)| Q(is_bestselling=True))

터미널에서 python shell을 실행한 후에

 

첫째줄을 실행하여 Q를 import해주고

두번째 조건문으로 조회를 하고자 했다.

 

이 or 조건은 rating이 3보다 작거나

베스트셀링이 True인 값들을 필터링하여

리턴해준다.

 

정말 python식 sql같다.


#2-1 or조건에 and 조건을 붙인 것

from django.db.models import Q
Book.objects.filter(Q(rating__lt=3)| Q(is_bestselling=True), Q(author="Caribian"))

#1의 조건에 author가 Caribian인 사람을 찾아라 라는 and 조건이다.

즉, and는 콤마와 Q를 이용하면 된다.

 

#2-2 그냥 표현만 달리 한 and 식

from django.db.models import Q
Book.objects.filter(Q(rating__lt=3)| Q(is_bestselling=True), author="Caribian")

그저 이렇게 Q를 빼고 봐줘도 작동한다.

300x250