잊기

[python, django] django(장고) shell(셸)을 이용한 데이터 조작 본문

Python _ Django

[python, django] django(장고) shell(셸)을 이용한 데이터 조작

잊기 2023. 2. 23. 11:38

- python manage.py 명령어 ~ 

      manage.py 파일은 project 생성시 자동생성 되므로, 해당 project에 접속해야 사용 가능

 

- shell  : python 언어를 작성할 수 있는 공간 ( >>>의 역할, 주피터노트북의 shell과 같음)

 

Shell을 이용한 data 조작

  • python manage.py shell : 파이썬 셸을 이용하여 데이터를 간리할 수 있는 API ( django가 제공 )
  • exit() : shell 에서 나올 때
python manage.py shell

>>> from polls.models import Question, Choice
	# 생성한 polls app 의 Question 과 Choice 클래스 import
>>> from django.utils import timezone
	# Question 의 culomn : id(자동생성), question_text, pub_date  가 있으며
    # pub_date 에 사용할 timezone 클래스 import
>>> q = Question (question_text = "What's new?", pub_date = timezone.now())
>>> q.save()

>>> Question.objects.all()
	# Question 컬럼의 rows를 조회하는 ORM 문법
<QuerySet [<Question: 취미가 므야?>, <Question: What's new?>]> # 출력문
>>> Question.objects.all()[:3]
	# 건수 제한
  • select ( filter )의 다양한 활용
# filter 의 활용

	# QuerySet - select 문장 + ( ( where의 역할 )을 하는 filter 사용가능)
>>> Question.objects.filter(
...	question_text__startswith='What'	# 'What'으로 시작하는 row 검색
...	).exclude(
...		pub_date__gte=datetime.date.today()
...	).filter(
...		pub_date__gte=fromisoformat('2002, 1, 30')
...	)

Question.objects.filter(
	question_text__contains = "do"
)
	# 'do'를 포함한 row 조회

one_entry = Question.objects.get(pk=1)
one_entry
	# pk=1 인 one_entry만 조회
    
from djangto.utils import timezone
current_year = timezone.now().year
Question.objects.filter(pub_date__year = current_year)
	# 생성일자가 올해 인 데이터 조회
    
q = Question.objects.get(pk=2)
q.choice_set.all()
	# choice_set.all() : Question pk=2로 연결되어있는 choice column의 데이터 조회

q.choice_set.count()
	# choice_set.all() : Question pk=2로 연결되어있는 choice column의 데이터의 갯수
  • 데이터 수정(update) , 저장(save), 조회
q = Question.objects.get(pk=2)
q
	# pk = 2인 row 조회
q.question_text = ' What is your favorit hobby?'	# 내용 수정
q.save()
q

  • 데이터 삭제
>>> Question.objects.filter(question_text__contains='new')	# 조회, 출력 (하단)
<QuerySet [<Question: What's new?>]>
>>> Question.objects.filter(question_text__contains='new').delete()	# 삭제