Menu

Log in

Sign up

From beginner to master of web design, coding, infrastructure operation, business development and marketing

  • COURSES
  • HTML & CSS Introduction
  • HTML & CSS Coding with AI
  • Linux Introduction
  • Docker Basics
  • Git & GitHub Introduction
  • JavaScript Coding with AI
  • Django Introduction
  • AWS Basics
  • Figma Introduction
  • SEO Tutorial for Beginners
  • SEO with AI
  • OTHERS
  • About
  • Terms of Service
  • Privacy Policy

© 2024 D-Libro. All Rights Reserved

Django IntroductionChapter 3. Django Models and Databases

Django Models – ForeignKey (OneToMany Relationship)

Django Models – ForeignKey (OneToMany Relationship)

Creating One-To-Many Relationships with ForeignKey

To make a One-To-Many relationship, Django uses ForeignKey. There are two key arguments you need to specify.

  1. Related model name
  2. On_delete argument

As explained on the previous page, by specifying a related model name through the ForeignKey field, Django connects the field with the ID of the related model. The on_delete argument is used to define the behavior when an object of the related model is deleted.

There are three possible values for the on_delete argument.

  • CASCASE: deletes the object containing the ForeignKey.
  • PROTECT: prevents deletion of the referenced object by raising ProtectedError
  • RESTRICT: prevents deletion of the referenced object by raising RestrictedError

As the possible values are available in django.db.models, you need to write on_delete=models.CASCADE.

Practice

Objective:
Learn how to use ForeignKey

In this practice, we'll explain how to use ForeignKey to create One-To-Many Relationship. In this case example, we'll add a division field in the Employee model by connecting it with the Division model.

1. Add a new field in the Employee model in models.py

Edit the Employee model in the models.py file to connect with the Division model.

  • Field name: division
  • Field type: ForeignKey
  • Related model name: Division
  • On_delete: models.CASCADE

The yellow line below is the new code.

employee_learning/models.py
from django.db import models
import datetime

class Employee(models.Model):

    PRIORITIES=[('H','High'), ('M','Medium'), ('L','Low'),]

    name=models.CharField(max_length=25, verbose_name="Employee Name")
    priority=models.CharField(max_length=1, choices=PRIORITIES, default="M", verbose_name="Learning Priorities")
    reg_date=models.DateField(default=datetime.date.today, verbose_name="Data Registration Date")
    division=models.ForeignKey(Division, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

2. Move the Division model before the Employee model in models.py

Cut the code of the Division model and paste the code before the Employee model in the models.py file. This is needed because the Employee model will refer to the Division model in the new field.

employee_learning/models.py
from django.db import models
import datetime

class Division(models.Model):
      :
    def __str__(self):
        return self.div_name

class Employee(models.Model):
      :

3. Run the makemigrations command

Run the makemigrations command.

Command Line - INPUT
python manage.py makemigrations employee_learning

As there are existing records, you'll encounter the message below.

Command Line - INTERACTIVE
It is impossible to add a non-nullable field 'division' to employee without specifying a default. This is because the database needs something to populate existing rows.
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit and manually define a default value in models.py.
Select an option: 

Answer 1 at this time. Then, the prompt is asking what data should be filled in.

Command Line - INTERACTIVE
Select an option: 1
Please enter the default value as valid Python.
The datetime and django.utils.timezone modules are available, so it is possible to provide e.g. timezone.now as a value.
Type 'exit' to exit this prompt
>>>

Here, you need to be careful. You should not input the data that is not available. As we need to input an available ID created in the Division model, type "1" for now.

Command Line - INTERACTIVE
>>> 1
Migrations for 'employee_learning':
employee_learning/migrations/0007_employee_division.py
- Add field division to employee

4. Migrate the model into the database and run the runserver

Complete the migration and run the runsever command.

Command Line - INPUT
python manage.py migrate
python manage.py runserver

5. Check the Django admin site

You can see that the Division model and the Employee model are connected. The employee model also reflects the data as we temporality input "1" for existing data. ID:1 is "Product Development" in this case.

Django Models – ForeignKey (OneToMany Relationship)

You can also learn this topic offline. Click AmazonKindle.

More Topics to Explore

How to Create HTML Templates in Django

Create HTML Templates

Defining Many-To-Many Relationships with ManyToManyField

Django Models – ManyToManyField

Restricting Page Access with LoginRequiredMixin

Login Required – LoginRequiredMixin

Integrating Bootstrap with Django Templates

Django Templates with Bootstrap

How to Create HTML Templates in Django

Create HTML Templates

Defining Many-To-Many Relationships with ManyToManyField

Django Models – ManyToManyField

Restricting Page Access with LoginRequiredMixin

Login Required – LoginRequiredMixin

Integrating Bootstrap with Django Templates

Django Templates with Bootstrap

Tags:

Django Models

ForeignKey

Relationship Fields

Django Introduction
Course Content

Chapter 1. Django Key Concepts

Web Framework and Django

Websites vs. Django Web Apps

How Django Handles HTTP Request and HTTP Response

Django's MVT Framework

Django Templates vs. Django APIs

Chapter 2. Django Quick Start Guide

Install Python

Install Visual Studio Code

Create Project Directory

Set Up Virtual Environment

Install Django

Start Django Project

Run Server

Database Migration

URL dispatcher – urls.py

Create Superuser and Log In to Django Admin

Start App

Create HTML Templates

Create Views

Add URL Patterns

Project vs. App

Chapter 3. Django Models and Databases

Create a Database in Django

Relational Database

Create Django Models

Makemigrations and Migrate

Add Models in Django Admin – admin.py

Change Display Name of Record Objects

Django Models – Data Field Type

Django Models – Field Options

Django Models – Help Text Option

Django Models – Choices Option

Django Models – DateField with datetime Module

Django Models – Relationship Fields

Django Models – ID

Django Models – ForeignKey (OneToMany Relationship)

Django Models – OneToOneField

Django Models – ManyToManyField

Chapter 4. Create CRUD Web Application

CRUD Web Application

Basic CRUD Structure in Django

Django Generic Views

How To Write Class-Based Views with Generic Views

Generic View Basic Attributes

URL Dispatcher for CRUD Views

Django Templates for CRUD Views

Django Template Language (DTL)

Template for List Page

get_FOO_display method

Template for Detail Page

Template with Model Relations

Template for Create and Update Page

Template for Delete Page

Add Links – {% url %} tag

Extend Templates – {% extends %} tag

Check Developing App UI on Mobile Device

Django Templates with Bootstrap

Crispy Forms

Customize Views (1) – Change List Order

Customizing Views (2) – Filter Lists

Context

Customize Views (3) – Add Extra Context

Modularize Templates – {% include %} tag

Static Files in Development Environment – {% static %} tag

STATIC_URL and STATICFILES_DIRS

Create Index HTML

Chapter 5. User Management

User Authentication

Overview of User Management Functions

User Management Function Development with Django

Approaches to Building User Management Functions in Django

Django Allauth (1) – Introduction

Django Allauth (2) – Installation and Initial Settings

Django Allauth (3) – Email Verification via Console

Django Allauth (4) – Email Verification via Gmail

Django Allauth (5) – Social Login with GitHub

Django Allauth (6) – Social Login with Google

Django Allauth (7) – Allauth Template File Setup

Django Allauth (8) – Add Basic Styling with Bootstrap and Crispy Forms

Django Allauth (9) – Customize Sign-in and Sign-up Pages

User Models

Login Required – LoginRequiredMixin

User Login Status Icon on Navigation Bar

Chapter 6. Deploy Django App

Overview of Django App Deployment (1)

Overview of Django App Deployment (2)

Key Steps of Django App Deployment

Hosting Service Initial Settings (1) – AWS Lightsail setup

Hosting Service Initial Settings (2) – SSH Remote Connection

Manage Local Computer and Remote Server Simultaneously

Tips for Managing Local Development and Remote Production Environment

Hosting Service Initial Settings (3) – Clone Project Directory with GitHub

Production Database Setup

Django Production Settings (1) – Settings.py for Development and Production

Django Production Settings (2) – Production Settings

Django Production Settings (3) – django-environ and .env file

Static File Settings

Django and Dependency Installation on Production Server

Web Server and Application Server in Django

Application Server Setup – Gunicorn

Web Server Setup – Nginx

Domain Setup

SSL Setup – Certbot

Email Setting – SendGrid

Social Login for Production

Manage Local Development and Remote Production Environment

Chapter 1. Django Key Concepts

Web Framework and Django

Websites vs. Django Web Apps

How Django Handles HTTP Request and HTTP Response

Django's MVT Framework

Django Templates vs. Django APIs

Chapter 2. Django Quick Start Guide

Install Python

Install Visual Studio Code

Create Project Directory

Set Up Virtual Environment

Install Django

Start Django Project

Run Server

Database Migration

URL dispatcher – urls.py

Create Superuser and Log In to Django Admin

Start App

Create HTML Templates

Create Views

Add URL Patterns

Project vs. App

Chapter 3. Django Models and Databases

Create a Database in Django

Relational Database

Create Django Models

Makemigrations and Migrate

Add Models in Django Admin – admin.py

Change Display Name of Record Objects

Django Models – Data Field Type

Django Models – Field Options

Django Models – Help Text Option

Django Models – Choices Option

Django Models – DateField with datetime Module

Django Models – Relationship Fields

Django Models – ID

Django Models – ForeignKey (OneToMany Relationship)

Django Models – OneToOneField

Django Models – ManyToManyField

Chapter 4. Create CRUD Web Application

CRUD Web Application

Basic CRUD Structure in Django

Django Generic Views

How To Write Class-Based Views with Generic Views

Generic View Basic Attributes

URL Dispatcher for CRUD Views

Django Templates for CRUD Views

Django Template Language (DTL)

Template for List Page

get_FOO_display method

Template for Detail Page

Template with Model Relations

Template for Create and Update Page

Template for Delete Page

Add Links – {% url %} tag

Extend Templates – {% extends %} tag

Check Developing App UI on Mobile Device

Django Templates with Bootstrap

Crispy Forms

Customize Views (1) – Change List Order

Customizing Views (2) – Filter Lists

Context

Customize Views (3) – Add Extra Context

Modularize Templates – {% include %} tag

Static Files in Development Environment – {% static %} tag

STATIC_URL and STATICFILES_DIRS

Create Index HTML

Chapter 5. User Management

User Authentication

Overview of User Management Functions

User Management Function Development with Django

Approaches to Building User Management Functions in Django

Django Allauth (1) – Introduction

Django Allauth (2) – Installation and Initial Settings

Django Allauth (3) – Email Verification via Console

Django Allauth (4) – Email Verification via Gmail

Django Allauth (5) – Social Login with GitHub

Django Allauth (6) – Social Login with Google

Django Allauth (7) – Allauth Template File Setup

Django Allauth (8) – Add Basic Styling with Bootstrap and Crispy Forms

Django Allauth (9) – Customize Sign-in and Sign-up Pages

User Models

Login Required – LoginRequiredMixin

User Login Status Icon on Navigation Bar

Chapter 6. Deploy Django App

Overview of Django App Deployment (1)

Overview of Django App Deployment (2)

Key Steps of Django App Deployment

Hosting Service Initial Settings (1) – AWS Lightsail setup

Hosting Service Initial Settings (2) – SSH Remote Connection

Manage Local Computer and Remote Server Simultaneously

Tips for Managing Local Development and Remote Production Environment

Hosting Service Initial Settings (3) – Clone Project Directory with GitHub

Production Database Setup

Django Production Settings (1) – Settings.py for Development and Production

Django Production Settings (2) – Production Settings

Django Production Settings (3) – django-environ and .env file

Static File Settings

Django and Dependency Installation on Production Server

Web Server and Application Server in Django

Application Server Setup – Gunicorn

Web Server Setup – Nginx

Domain Setup

SSL Setup – Certbot

Email Setting – SendGrid

Social Login for Production

Manage Local Development and Remote Production Environment