Django Tutorial
About Lesson

In this Django tutorial we want to learn about Django Many-To-One Relationships, there are different models relationships in django, we have Many-to-One Relationships, One-to-One Relationships and Many-to-Many Relationships. basically in this lesson we want to learn about Django Many-to-One Relationships, so a many to one relationship implies that one model record can have many other model records associated  with itself.  To define this relationship in Django models you use  the ForeignKey data type on the model that has the many records .

 

 

In this example we want to create a new Choice model and we want to create a many-to-one Relationship between the Question and Choice model, so this is our model basically we have three fields for this model and the first field is the relationship field.

 

 

So this is our complete models.py file.

 

 

 

After creating of a new model in django, you need to do migration and after that migrate your project.

 

So after doing this you will see that we have added a table in to our database.

 

 

Now let’s register our this model in our admin.py file, so open your admin.py file and add this.

 

 

 

This is our complete admin.py file.

 

 

 

And this is our django admin panel.

Django Many-to-One Relationships
Django Many-to-One Relationships

 

 

 

Rest of the file for this tutorial.

 

 

mysite/templates/base.html

 

 

 

mysite/templates/navbar.html

 

 

mysite/templates/index.html

 

 

mysite/templates/polls_list.html

 

 

 

mysite/polls/views.py

 

 

mysite/polls/urls.py

 

 

 

mysite/urls.py

Thank you for visiting my website! If you enjoyed the free courses, please consider supporting my works on Patreon.
Exercise Files
No Attachment Found
No Attachment Found