kb84tkhrのブログ

何を書こうか考え中です あ、あと組織とは関係ないってやつです 個人的なやつ

Djangoチュートリアル(3) モデルへのアクセス

ちょっと長丁場になってきてませんか

モデルをイジります
Pythonシェルを起動

$ python manage.py shell
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

(InteractiveConsole)と言っている以外は普通のREPL
最初はからっぽ

>>> from polls.models import Question, Choice
>>> Question.objects.all()
<QuerySet []>

Questionオブジェクトを作って保存

>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()

データベースにレコードができてる

sqlite> select * from polls_question;
1|What's new?|2019-06-25 12:11:40.161324

いったんREPLを出てQuestionクラスとChoiceクラスにメソッドを追加
__str__()はadminでも使うらしいので大事なとこ

class Question(models.Model):
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    def __str__(self):
        return self.choice_text

再度Python Shellを起動するとデータベースからデータが読まれた状態になってる
本文ではさらっとスルーされてるけどここはびっくりしておくところなのでは
どういうタイミングでデータベースから読み込んでるんだろう
モジュール起動時とか手動で読み込んだ時だけかな?
いつも最新?

試す

sqlite> insert into polls_question("question_text", "pub_date") values ("Second Question", CURRENT_TIMESTAMP);
sqlite> select * from polls_question;
1|What's new?|2019-06-25 12:11:40.161324
2|Second Question|2019-06-25 12:54:18

どうかな

>>> Question.objects.all()
<QuerySet [<Question: What's new?>, <Question: Second Question>]>

お、更新されてる
なかなかやるな
ヨソで更新されてるかもとか思わずガンガン使えばいいのかなあ

あとはいろんな操作を体験

>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's new?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's new?>]>
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/takahiro/study/django-tutorial/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/takahiro/study/django-tutorial/venv/lib/python3.6/site-packages/django/db/models/query.py", line 384, in get
    (self.model._meta.object_name, num)
polls.models.MultipleObjectsReturned: get() returned more than one Question -- it returned 2!

勝手にレコード追加したからな
複数変える可能性が有るときはたぶん聞き方がちがうってことだろう

>>> Question.objects.get(id=2)
<Question: Second Question>
>>> Question.objects.get(id=3)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/takahiro/study/django-tutorial/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/takahiro/study/django-tutorial/venv/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get
    self.model._meta.object_name
polls.models.DoesNotExist: Question matching query does not exist.
>>> Question.objects.get(pk=1)
<Question: What's new?>
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
>>> c.question
<Question: What's new?>
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
(1, {'polls.Choice': 1})
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>]>