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.
1 2 3 4 |
class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) |
So this is our complete models.py file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from django.db import models # Create your models here. class Question(models.Model): text = models.CharField(max_length=100) pub_date = models.DateTimeField('date published') def __str__(self): return self.text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.text |
After creating of a new model in django, you need to do migration and after that migrate your project.
1 |
python manage.py makemigrations |
1 |
python manage.py migrate |
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.
1 |
admin.site.register(Choice) |
This is our complete admin.py file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
from django.contrib import admin from .models import Question, Choice # Register your models here. #first way #admin.site.register(Question) #second way @admin.register(Question) class QuestionModel(admin.ModelAdmin): list_filter = ('text', 'pub_date') list_display = ('text', 'pub_date') date_hierarchy = ('pub_date') ordering = ('pub_date', 'text') admin.site.register(Choice) |
And this is our django admin panel.
Rest of the file for this tutorial.
mysite/templates/base.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <!-- CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" > <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> {% include 'navbar.html' %} {% block body %} {% endblock %} <!-- jQuery and JS bundle w/ Popper.js --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" > </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/ bootstrap.bundle.min.js" ></script> </body> </html> |
mysite/templates/navbar.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<nav class="navbar navbar-expand-lg navbar navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'index' %}">GeeksCoders</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link active" href="{% url 'index' %}">Home <span class="sr-only">(current)</span></a> <a class="nav-link" href="{% url 'polls_list' %}">Polls</a> </div> </div> </nav> |
mysite/templates/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{% extends 'base.html' %} {% block title %} Home {% endblock %} {% block body %} <div class="container"> <h1>Welcome to GeeksCoders.com</h1> <p>Tutorial Number 13 - Many to One Relationship</p> </div> {% endblock %} |
mysite/templates/polls_list.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
{% extends 'base.html' %} {% block title %} Polls List {% endblock %} {% block body %} <div class="container"> <h1>Polls List Page</h1> {% for poll in polls %} <ul class="list-group"> <li class="list-group-item"> {{poll}} </li> </ul> {% endfor %} </div> {% endblock %} |
mysite/polls/views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
from django.shortcuts import render from .models import Question # Create your views here. def Index(request): context = {} return render(request, 'index.html', context) def Polls(request): polls = Question.objects.all() context = {'polls':polls} return render(request, 'polls_list.html', context) |
mysite/polls/urls.py
1 2 3 4 5 6 |
from django.urls import path from .views import Index, Polls urlpatterns = [ path('', Index, name = 'index'), path('polls/', Polls, name = 'polls_list') ] |
mysite/urls.py
1 2 3 4 5 6 7 |
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('polls.urls')) ] |