7- How to Create a Django Model with Questions and Choices

In this article, we will show you how to create a Django model with questions and choices. You will learn how to use the Python shell to create and save a new question object in the database, access model field values using Python attributes, and create multiple choices for your question. Follow along with our step-by-step guide to get started with Django models and build your interactive web applications.

To invoke the Python shell, use this command:

py manage.py shell

Once you’re in the shell:

from polls.models import Choice, Question

Create a new Question.

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

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

q.save()

Now it has an ID.

q.id
#1

Access model field values via Python attributes.

q.question_text

'Rate this tutorial:'

q.pub_date

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()

In conclusion, this article provides a step-by-step guide to creating a Django model with questions and choices. It demonstrates how to use the Python shell to create and save a new question object in the database, access model field values using Python attributes, and create multiple choices for the question. By following this guide, readers can get started with Django models and build their interactive web applications.

If you find this content helpful, please consider subscribing to my channel for future updates.

Did you find this article valuable?

Support Azad Rasul by becoming a sponsor. Any amount is appreciated!