프로그래밍/Python & dJango
[dJango] Q expression
bbuljj
2016. 10. 19. 17:35
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'))