DEV Community

Dr. Azad Rasul
Dr. Azad Rasul

Posted on

7- Django: reate a new question and choices

To invoke the Python shell, use this command:

py manage.py shell
Enter fullscreen mode Exit fullscreen mode

Once you’re in the shell:

from polls.models import Choice, Question
Enter fullscreen mode Exit fullscreen mode

Create a new Question.

from django.utils import timezone
q = Question(question_text="Rate this tutorial:", pub_date=timezone.now())
Enter fullscreen mode Exit fullscreen mode

Save the object into the database. You have to call save() explicitly.

q.save()
Enter fullscreen mode Exit fullscreen mode

Now it has an ID.

q.id
#1
Enter fullscreen mode Exit fullscreen mode

Access model field values via Python attributes.

q.question_text
Enter fullscreen mode Exit fullscreen mode

'Rate this tutorial:'

q.pub_date
Enter fullscreen mode Exit fullscreen mode

datetime.datetime(2022, 5, 14, 15, 41, 26, 711723, tzinfo=datetime.timezone.utc)

Create five choices:

q.choice_set.create(choice_text='*', votes=0)
q.choice_set.create(choice_text='**', votes=0)
q.choice_set.create(choice_text='***', votes=0)
q.choice_set.create(choice_text='****', votes=0)
q.choice_set.create(choice_text='*****', votes=0)

q.choice_set.all()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)