[dJango] Q expression

2016. 10. 19. 17:35프로그래밍/Python & dJango

1. 장고에서 제공하는 Q expression에 대해서 알아보자.


 - Q expression


    A 란 테이블(model)의 title 이  'hello' 인 row를 가져온다고 가정했을 때 아래와 같이 작성할 수 있다.


from common.A.models import A
result = A.objects.filter(title='hello')


    위의 코드를 Q expression을 사용하면 아래와 같이 작성할 수 있다.


from common.A.models import A
from django.db.models import Q
result = A.objects.filter(Q(title='hello'))


   또, and 와 or 조건을 추가할 수 있다.


   예를들어 title이 'hello' 이고, sub_title이 'world'인 row를 가져 와야 한다면, 아래와 같이 작성할 수 있다.

from common.A.models import A
from django.db.models import Q
result = A.objects.filter(Q(title='test1')) 
                & A.objects.filter(Q(sub_title='world'))


'프로그래밍 > Python & dJango' 카테고리의 다른 글

[Python] 집합 (set)  (0) 2016.10.19
[django] convert integer to string  (0) 2016.10.19
[Python] closure  (0) 2016.10.07
Python 환경변수 가져오기.  (0) 2016.10.05
[Python] map, filter, reduce  (0) 2016.10.04