Notice
Recent Posts
Recent Comments
Link
터칭 데이터
장고(Django) 모델 필터링(Model Filtering) 2 본문
필터의 인자에 넣을 수 있는 조건문들은 여러개가 있습니다.
https://docs.djangoproject.com/en/4.2/ref/models/querysets/#field-lookups
Django
The web framework for perfectionists with deadlines.
docs.djangoproject.com
우리가 프로그래밍에 익숙하다면 크게 어렵지 않은 조건문들인데요.
다만 정규표현식(regex)는 다소 생소할 수도 있으나 매우 강력하고 유용한 기능이니
파이썬에서 정규표현식 DOCS를 자주 읽고 실습하기를 권장합니다.
장고의 filter()에서의 정규표현식과 파이썬에서의 정규표현식은 같습니다.
https://docs.python.org/ko/3/howto/regex.html
Regular Expression HOWTO
Author, A.M. Kuchling < amk@amk.ca>,. Abstract: This document is an introductory tutorial to using regular expressions in Python with the re module. It provides a gentler introduction than the corr...
docs.python.org
>>> from polls.models import *
#startswith 연산자를 활용하여 오브젝트를 필터링하기
>>> q = Question.objects.filter(question_text__startswith='휴가를')
>>> q2 = Question.objects.filter(pub_date__year=2023)
#contains 연산자를 활용하여 오브젝트를 필터링하기
>>> Question.objects.filter(question_text__contains='휴가')
>>> Choice.objects.all()
>>> Choice.objects.filter(votes__gt=0)
#해당 쿼리셋에 대한 SQL 쿼리를 생성하기
>>> Choice.objects.filter(votes__gt=0).query
>>> print(Choice.objects.filter(votes__gt=0).query)
SELECT "polls_choice"."id", "polls_choice"."question_id", "polls_choice"."choice_text", "polls_choice"."votes" FROM "polls_choice" WHERE "polls_choice"."votes" > 0
>>> choice=Choice.objects.first()
>>> choice.votes=5
>>> choice.save()
#정규표현식을 활용하여 조건에 해당하는 오브젝트들을 필터링하기
>>> Question.objects.filter(question_text__regex=r'^휴가.*어디')
>>> print(Question.objects.filter(question_text__regex=r'^휴가.*어디').query)
SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date", "polls_question"."owner_id" FROM "polls_question" WHERE "polls_question"."question_text" REGEXP ^휴가.*어디
정규표현식 대신
>>> q = Question.objects.filter(question_text__startswith='휴가를').filter(question_text__contains='어디서')
>>> q
<QuerySet [<Question: 제목: 휴가를 어디서 보내고 싶으세요?, 날짜: 2023-10-31 14:19:40+00:00>]>
위와 같이 filter를 여러번 꼬리물듯이 작성해도 결과는 똑같습니다. 다만 정규표현식은 정규표현식대로의 강점이 있으므로 학습해두시기를 한번 더 권해드립니다.
'장고 (Django)' 카테고리의 다른 글
장고(Django) 모델 메소드 (0) | 2023.11.02 |
---|---|
장고(Django) 모델 관계기반 필터링 (0) | 2023.11.02 |
장고(Django) 모델 필터링(Model Filtering) (0) | 2023.11.01 |
장고(Django) 쉘에서 데이터 수정하고 삭제하기 (0) | 2023.11.01 |
장고(Django) 쉘에서 데이터 입력하기 (0) | 2023.11.01 |