24. (app2) Django Shell로 Model 조작하기2
1. Choice 모델 객체 만들기(1)
- Choice 는 Question에 연관되어진 모델이기 때문에 q2 = Choice(..., ..., ...) 과 같이 바로 만들 수 없다.
- 때문에 아래와 같이 Question을 먼저 생성하고나서 생성을 진행해야 한다.
- 그 후 Choice는 생성된 Question 객체.choice_set.create() 방식으로 생성하게 된다.
- "q = Question(question_text = "최고의 고기는?", pub_date = timezone.now())"
- "q.save()"
- "q.choice_set.create(choice_text = "돼지")"
- "q.choice_set.create(choice_text = "치킨")"
- "q.choice_set.create(choice_text = "소")"
2. Choice 모델 객체 만들기(2)
- "q2 = Question(question_text = "짜장? 짬뽕?", pub_date = timezone.now())"
- "q2.save()"
- "q2.choice_set.create(choice_text = "짜장")"
- "q2.choice_set.create(choice_text = "짬뽕")"
- "q2.choice_set.create(choice_text = "탕슉")"
3. Choice 모델 객체 가져오기
- 연관된 모델의 객체.choice_set.all() 을 통해 가져올 수 있다.
- "q.choice_set.all()" -> <QuerySet [<Choice: 돼지>, <Choice: 치킨>, <Choice: 소>]>
- "q2.choice_set.all()" -> <QuerySet [<Choice: 짜장>, <Choice: 짬뽕>, <Choice: 탕슉>]>
- "Choice.objects.all()" -> 이 방식은 모델간의 관계가 보여지지 않으므로 잘 사용하지 않음.