본문 바로가기
Django

[Django] python shell로 데이터 CRUD

by 기록하는_사람 2022. 12. 12.

가상 환경으로 python shell 실행하기

📌 가상 환경으로 python shell 실행하기

python manage.py shell

 

데이터 추가하기

📌 데이터 추가하기

// 'test' app의 Student 테이블 데이터 
from test.models import Student

st = Student(name="kim", age=30, subject="eng").save()
st = Student(name="lee", age=26, subject="kor").save()
st = Student(name="park", age=29, subject="math").save()

 

데이터 조회하기

📌 데이터 한 개 조회하기

s1 = Student.objects.get(name="kim")
s1  // 확인
s1.name, s1.age, s1.subject, s1.id

 

💡 보통 .get()은 중복이 없는 primary key를 사용함.

 

📌 데이터 전체 조회하기

s2 = Student.objects.all()
s2  // 확인

for i in s2:
	i.name, i.age, i.subject, i.id  // 하나씩 출력

 

데이터 수정하기

📌 데이터 수정하기

s1 = Student.objects.get(id=1)
s1.age = 20
s1.save()
s1.age  // 확인

 

데이터 삭제하기

📌 데이터 삭제하기

s1 = Student.objects.get(id=2)
s1.delete()
Student.objects.all()  // 확인

 

python shell 종료

📌 python shell 종료

quit()

 

댓글