Skip to content

Model Relationships

Kory Mayberry edited this page Sep 27, 2023 · 9 revisions

Overview

A relational database is a structured collection of data organized in a way that allows for efficient storage, retrieval, and manipulation of information. It is based on the principles of the relational model. In a relational database, data is organized into tables, where each table consists of rows (records) and columns (attributes). The relationships between the tables are defined by common fields (keys), allowing for the establishment of connections and dependencies between data sets. This relational structure enables data integrity, scalability, and the ability to perform complex queries and transactions. SQL (Structured Query Language) is commonly used to interact with and manage relational databases. In Django, SQL is abstracted out so it is easier to query databases.

Relationships

One-to-One

This relationship is rare in practice. It references that one entry in table A is related to one entry in table B. An example of this might be an instance where a users login information is separate from account details. Each login can only be associated with one account, another example would be the relationship in the picture below, where one student in the student table has one address in the address table.

Screenshot 2023-09-27 at 3 42 58 PM

In Django, there is a field type syntax to declaring something in a model class as one-to-one.

class Model1(models.Model):
    # Fields for Model1

class Model2(models.Model):
    model1 = models.OneToOneField(Model1, on_delete=models.CASCADE)
    # Other fields for Model2

One-to-Many

Many-to-Many

Many-to-One

Clone this wiki locally