파이썬 쉘은 파이썬 콘솔로 db를 관리할 수 있게 해준다.
1. shell 진입
python manage.py shell 로 진입한다.
만약
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published') #p144 참조
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
|
cs |
이런 models.py 가 있다고 해보자
a.insert
insert는 다음과 같이 입력한다. 마지막의 save() 로 insert를 하는게 마치 jpa 랑 비슷하다.
>>>from polls.models import Question, Choice
>>>from django.utils import timezone
>>>q = Qustion(question_text="새로운 것", pub_date=timezone.now())
>>>q.save()
b. select
다음과 같이 입력하자
>>>Question.objects.all()
이 결과는 <QuerySet [<Question: what's new?>, <Question: new>]> 와 같이 나온다.
즉, 연산의 결과로 QuerySet 콜렉션을 반환한다.
일부의 레코드만검색할 때에는 filter()와 exclude() 메소드를 사용한다.
filter()는 주어진 조건에 맞는 객체들을 담고 있는 QuerySet을 리턴하고
exclude()는 조건에 맞는 객체를 제외한다.
>>>Question.objects.filter(
question_text__startswith=='what'
).exclude(
pub_date__gte=datetime.date.today()
).filter(
pub_date__gte=datetime(2005, 1, 30)
)
위의 식은 what으로 시작하는 것 중에서 오늘날짜 보다 크거나 같은 것은 제외하고
2005,1,30 이후에 있는 것들만 추리는 것이다.
__startswith 은 시작하는 것
__gte 는 greater than + equl 이라 생각하자 이들은 쉘 연산자이다.
한개의 요소만 있는 것이 확실한 경우 get() 메소드로 하나의 객체를 가져온다.
>>>one_entry = Question.objects.get(pk=1)
querySet 요소를 제한하기 위해 슬라이싱도 가능하다.
아마 이런형태의 문장들은 views.py에서도 봤을 것이다.
c.update
하나의 객체를 수정하고자 할 때에는 save()를 사용한다.
a. 항목의 변수 q를 사용한다고 할 때
>>>q.question_text = "새애로운것"
>>>q.save()
이러면 q에 마지막으로 정의가 된 Question 객체의 question_text 가 update된다.
여러개의 객체의 수정을 하려면 update() 를 사용한다.
>>>Question.objects.filter(pub_date__year=2007).update(question_text='일괄 새로움')
하면 2007년에 쓰여진 모든 객체들의 question_text가 변경된다.
d.delete
delete()를 쓴다. 역시 filter() 를 사용할 수 있다.
>>>Question.objects.filter(pub_date__year=2005).delete()
모든 객체를 지우고 싶다면 all().delete()를 쓰면 된다.
Question.objects.all().delete()
e.모델에서의 __str__(self)
__str__ 이 만약 없다면 레코드의 제목이 Question:Question object 처럼 나올 것이다.
__str__(self) 는 객체를 알아보기 쉬운 문자열로 표시하기 위해 사용한다.
f. 참조 관계의 처리
Question 과 Choice 가 1:N 의 관계로 있고, Choice가 Question_id 를 fk로 가지고 있다고 할 때
Choice -->Question 방향일 때에는 question 속성,
Question -->Choice 방향일 때에는 choice_set 속성을 사용한다.
예를 들어보자
>>>q=Question.objects.get(pk=2) #pk=2 인 오브젝트를 q에 저장
>>>q.choie_set.all() #pk=2 인 choice 객체 전체 조회
>>>q.choice_set.create(choice_text='djmax', votes=0) #Choice 테이블에 다음과 같은 레코드 생성
>>>q.choice_set.create(choice_text='rainbowsixSiege' ,votes=0)
>>>q.choice_set.create(choice_text='tekken' ,votes=0)
>>>c = q.choice_set.create(choice_text='civilization' ,votes=0) #Choice 테이블에 레코드 만들고 변수에 저장
>>>c = c.question #c 객체와 연결된 Question 객체 조회
>>>q.choice_set.all() #q 즉, Question 레코드 중 pk=2 인 choice_set 전체 조회
>>>q.choice_set.count() #choice_set 의 개수 조회