8. Django Shell 사용하기
polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return f'제목: {self.question_text}, 날짜: {self.pub_date}'
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 f'{self.choice_text}'
Django Shell 실행하기
python manage.py shell
#models.py 파일에 정의된 모든 모델 가져오기
>>> from polls.models import *
>>> Question
#모든 Question,Choice 오브젝트 가져오기
>>> Question.objects.all()
>>> Choice.objects.all()
#첫번째 Choice 오브젝트 가져오기
>>> choice = Choice.objects.all()[0]
>>> choice.id
>>> choice.choice_text
>>> choice.votes
#첫번째 Choice와 연결된 Question 가져오기
>>> choice.question
>>> choice.question.pub_date
>>> choice.question.id
#해당 Question과 연결되어 있는 모든 Choice 가져오기
>>> question.choice_set.all()
9. Django Shell - 현재 시간 구하기
# datetime 활용
>>> from datetime import datetime
>>> datetime.now()
# timezone 활용
>>> from django.utils import timezone
>>> timezone.now()
10. Django Shell - 레코드 생성하기
>>> from polls.models import *
>>> q1 = Question(question_text = "커피 vs 녹차")
>>> from django.utils import timezone
>>> q1.pub_date = timezone.now()
>>> q1.save()
polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(auto_now_add=True)
>>> q3 = Question(question_text = "abc")
>>> q3.pub_date = timezone.now()
>>> q3.save()
>>> q3.choice_set.create(choice_text = "b")
>>> choice_c = Choice(choice_text='c', question=q3)
>>> choice_c.save()
11. Django Shell - 레코드 수정 및 삭제 하기
>>> from polls.models import *
# 수정하기
>>> q = Question.objects.last()
>>> q.question_text = q.question_text + '???'
>>> choice = Question.objects.last()
# 삭제하기
>>> choice.queston.choice_set.all()
>>> choice.delete()
12. Django Shell - 모델 필터링(Model Filtering)
>>> from polls.models import *
# get() 활용
>>> Question.objects.get(id=1)
>>> q = Question.objects.get(question_text__startswith='휴가를')
>>> Question.objects.get(pub_date__year=2023) # 에러발생
polls.models.Question.MultipleObjectsReturned: get() returned more than one Question
# filter() 활용
>>> Question.objects.filter(pub_date__year=2023)
<QuerySet [<Question: 제목: 휴가를 어디서 보내고 싶으세요?, 날짜: 2023-02-05 18:52:59+00:00>, <Question: 제목: 가장 좋아하는 디저트는?, 날짜: 2023-02-05 18:53:27+00:00>, ...]>
>>> Question.objects.filter(pub_date__year=2023).count()
#쿼리셋의 SQL 쿼리
>>> Question.objects.filter(pub_date__year=2023).query
>>> print(Question.objects.filter(pub_date__year=2023).query)
SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date" FROM "polls_question" WHERE "polls_question"."pub_date" BETWEEN 2023-01-01 00:00:00 AND 2023-12-31 23:59:59.999999
>>> Question.objects.filter(question_text__startswith='휴가를').query
>>> print(Question.objects.filter(question_text__startswith='휴가를').query)
SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date" FROM "polls_question" WHERE "polls_question"."question_text" LIKE 휴가를% ESCAPE '\'
>>> q = Question.objects.get(pk=1)
>>> q.choice_set.all()
>>> print(q.choice_set.all().query)
SELECT "polls_choice"."id", "polls_choice"."question_id", "polls_choice"."choice_text", "polls_choice"."votes" FROM "polls_choice" WHERE "polls_choice"."question_id" = 1
13. 모델 필터링(Model Filtering) 2
>>> from polls.models import *
# startswith 활용
>>> q = Question.objects.filter(question_text__startswith='휴가를')
>>> q2 = Question.objects.filter(pub_date__year=2023)
# contains 활용
>>> Question.objects.filter(question_text__contains='휴가')
>>> Choice.objects.all()
>>> Choice.objects.filter(votes__gt=0)
# 쿼리셋 SQL 쿼리
>>> Choice.objects.filter(votes__gt=0).query
>>> print(Choice.objects.filter(votes__gt=0).query)
SELECT "polls_choice"."id", "polls_choice"."question_id", "polls_choice"."choice_text", "polls_choice"."votes" FROM "polls_choice" WHERE "polls_choice"."votes" > 0
>>> choice=Choice.objects.first()
>>> choice.votes=5
>>> choice.save()
# 정규표현식 활용
>>> Question.objects.filter(question_text__regex=r'^휴가.*어디')
>>> print(Question.objects.filter(question_text__regex=r'^휴가.*어디').query)
SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date", "polls_question"."owner_id" FROM "polls_question" WHERE "polls_question"."question_text" REGEXP ^휴가.*어디
14. Django 모델 관계기반 필터링
polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return f'제목: {self.question_text}, 날짜: {self.pub_date}'
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 f'[{self.question.question_text}] {self.choice_text}'
>>> from polls.models import *
>>> Choice.objects.filter(question__question_text__startswith='휴가')
# exclude() 활용
>>> Question.objects.exclude(question_text__startswith='휴가')
15. Django Shell - 모델 메소드
polls/models.py
from django.utils import timezone
import datetime
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def __str__(self):
if self.was_published_recently():
new_badge = 'NEW!!!'
else:
new_badge = ''
return f'{new_badge} 제목: {self.question_text}, 날짜: {self.pub_date}'
'데브코스 TIL > Django, API' 카테고리의 다른 글
Django REST Framework Part 2 (0) | 2023.11.06 |
---|---|
Django REST Framework Part 1 (0) | 2023.11.06 |
Django Tutorial Part 4 (0) | 2023.11.06 |
Django Tutorial Part 3 (0) | 2023.11.06 |
Django Tutorial Part 1 (0) | 2023.11.06 |