Programing/Python

[django] shell 사용하기

mjune.kim 2019. 4. 9. 12:22

이번에는 장고 셸을 이용해 데이터베이스에 저장된 값을 출력해보거나 데이터를 추가하는 방법에 대해 알아보겠습니다.

1. shell 실행하기

$> python manage.py shell

2. Candidate object 에 저장된 데이터 모두 가져오기

>>> candidates = Candidate.objects.all()

3. 특정 조건을 만족하는 데이터만 가져오기

>>> no1 = Candidate.objects.filter(party_number = 1)
 
mysite$ python manage.py shell
Python 3.6.7 (default, Oct 22 201811:32:17
[GCC 8.2.0] on linux
Type "help""copyright""credits" or "license" for more information.
(InteractiveConsole)
>>> from elections.models import Candidate
>>> Candidate.objects.all()
<QuerySet [<Candidate: James><Candidate: Paul>]>
>>> new_candidate = Candidate(name="Lubio")
>>> Candidate.objects.all()
<QuerySet [<Candidate: James><Candidate: Paul>]>
>>> new_candidate.save()
>>> Candidate.objects.all()
<QuerySet [<Candidate: James><Candidate: Paul><Candidate: Lubio>]>
>>> no1 = Candidate.objects.filter(party_number=1)
>>> no1
<QuerySet [<Candidate: James><Candidate: Lubio>]>
>>> no1[1]
<Candidate: Lubio>
>>> no1[1].party_number
1
 
cs

 

※ 해당 내용은 programmers.co.kr 강의를 수강한 후 정리한 내용입니다.