ruk·si

🍡 Django Tutorial
Interactive Console

Updated at 2018-11-23 18:02

Interactive console is handy for debugging and ASAP production fixes.

python manage.py shell

from polls.models import Question
from django.contrib.auth import get_user_model
from django.utils import timezone

Question.objects.all() # => <QuerySet []>
q = Question(text="What's new?")
q.id
q.author = get_user_model().objects.create()
q.text
q.created_at
q.text = "What's up?"
q.save()
q.created_at
Question.objects.all() # => <QuerySet [<Question: Question object (...)>]>

Edit polls/models/*.py:

class Question(models.Model):
    # ...
    def __str__(self) -> str:
        return self.text

class Choice(models.Model):
    # ...
    def __str__(self) -> str:
        return self.text

Try it again:

python manage.py shell
from polls.models import Question
Question.objects.all() # => <QuerySet [<Question: What's up?>]>

Edit polls/models/question.py:

from datetime import timedelta
from django.db import models
from django.utils import timezone

class Question(models.Model):
    # ...

    def was_created_recently(self) -> bool:
        return self.created_at >= timezone.now() - timedelta(days=1)

Try the new method:

python manage.py shell

from polls.models import Question, Choice
Question.objects.first() # => <QuerySet [<Question: What's up?>]>
Question.objects.filter(text__startswith='What') # the same, but a list

from django.utils import timezone
current_year = timezone.now().year
Question.objects.get(created_at__year=current_year) # => the same

Question.objects.get(id=2) # => error, pk is UUID
q = Question.objects.first()
q.was_created_recently() # => True

q.choices.all() # => <QuerySet []>
q.choices.create(text='Not much')
q.choices.create(text='The sky', votes=1)
c = q.choices.create(text='Just hacking again')
c.question              # => <Question: What's up?>
q.choices.all()      # => <QuerySet [<Choice: Just hacking again>, ...]>
q.choices.count()    # => 3
Choice.objects.filter(question__created_at__year=current_year) # => the same

c = q.choices.filter(text__startswith='Just hacking')
c.delete()
q.choices.count() # => 2