Django Models Fundamentals: A complete guide to understanding database structure with ease

Hello, everyone! Today we're going to learn the basics of Django models. Let's start with the first Djangothe concept of models seemed a bit foreign and intimidating to you. I know it did to me. But don't worry, this post will give you a thorough understanding of the basics of Django models and database structure.

Django models are at the heart of database design. They're a magical tool that lets you manipulate databases with Python code without the need for complex SQL queries. In this post, we'll cover everything you need to know about Django models, from basic concepts to real-world code examples. So, let's get started!

What are Django Models?

Django models store the database structure in a Python ClassesEach model corresponds to a table in the database, and the properties of the model become fields in the table. Django uses this model to abstract database operations, making it easier for developers to work with data.

Database structure (tables and fields)


Database tablesis an Excel file's One sheetfor example. An Excel sheet has multiple rows (rows) and columns (columns), right? Similarly, a table organizes data into rows (records) and columns (fields).
- Row: Represents a single piece of data. Example.) In the Customers table, a row represents one customer's information
- Column: Represents an attribute of the data. For example.) Customer's name, email, and phone number

Fieldsis the Each columnThis means that one field can be used to represent the Propertiesor Featuresin the table. For example, if you're creating a customer table, you'll need fields like ID, Name, Email, Phone, etc.

Django Models Basics: Creating your first model

Django models 기초 참고 이미지
(Django models basics reference image - Classes and tables )

Now, let's actually create a Django model. Take a look at the code below, which creates a model called 'Book' to create a structure for storing and managing book information (chapters title, author, publication date, book price)

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    publication_date = models.DateField()
    price = models.DecimalField(max_digits=6, decimal_places=2)

    def __str__(self):
        return self.title

Code commentary

  1. from django.db import models: imports to use Django's model functionality.
  2. class Book(models.Model): Define a model class named 'Book'. models.Modelto InheritanceAnswer.
  3. title = models.CharField(max_length=200)Defines a string field to store the book title. It can store up to 200 characters.
  4. author = models.CharField(max_length=100): Field to store the author name. It can be up to 100 characters.
  5. publication_date = models.DateField()Date field to store the publication date.
  6. price = models.DecimalField(max_digits=6, decimal_places=2)The decimal field to store the price in. You can store up to 6 digits and 2 decimal places.
  7. def __str__(self):: This method is used to represent an instance of the model as a string. Here, we've chosen to return the title of the book.

And there you have it, a basic Django model! It seems complicated, but when you put it all together, it's not that hard, right? What do you do if you don't understand? You just go, "Oh, this is what it is," and then you realize that this is the floor.

Understanding Django Models and database structure

Django models make it easy to define your database structure. The Book model above actually creates the following tables in the database

CREATE TABLE "books_book" (
    "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
    "title" varchar(200) NOT NULL,
    "author" varchar(100) NOT NULL,
    "publication_date" date NOT NULL,
    "price" decimal(6, 2) NOT NULL
);

Code commentary

The SQL code is a translation of the Django model we saw earlier into a database table. This code is a SQL command that creates a table called 'books_book'.

  1. Table name: "books_book"
    • By default, Django creates table names by combining the app name and model name. Here, this means the 'Book' model for the 'books' app.
  2. Field definitions
    • "id": An integer field, which is a PRIMARY KEY and has the AUTOINCREMENT property.
    • "title": A variable-length string (varchar) field of up to 200 characters.
    • "author": A variable-length string field of up to 100 characters.
    • "publication_date": A date (DATE) type field.
    • "price": A decimal field of up to 6 digits, including 2 decimal places.
  3. Constraints:
    • All fields have a NOT NULL constraint to disallow null values.

As you can see, Django models automatically convert your Python code to SQL for you - that's the magic of the Django Object-Relational Mapping (ORM)!

Django Models Fundamentals: Setting up relationships

(Django models basics reference image - Setting up relationships )

One of the most important concepts in databases is relationships, and Django models make it easy to represent them.

class Publisher(models.Model):
    name = models.CharField(max_length=200)
    address = models.CharField(max_length=200)

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey('Author', on_delete=models.CASCADE)
    publisher = models.ForeignKey(Publisher, on_delete=models.SET_NULL, null=True)
    genres = models.ManyToManyField('Genre')

Code commentary

  1. author = models.ForeignKey('Author', on_delete=models.CASCADE): This represents a one-to-many (1:N) relationship: one author can write multiple books. on_delete=models.CASCADEmeans that when an author is deleted, all of their books are also deleted.
  2. publisher = models.ForeignKey(Publisher, on_delete=models.SET_NULL, null=True): This is also a one-to-many relationship: one publisher can publish multiple books. on_delete=models.SET_NULLmeans that if the publisher is deleted, the publisher field for the book will be set to NULL (True).
  3. genres = models.ManyToManyField('Genre')This represents a many-to-many (N:N) relationship: a book can belong to multiple genres, and a genre can belong to multiple books.

This is how Django models make it easy to represent complex database relationships.

Django Models basics: Database Migration

Django models 기초 참고 이미지 - 데이터베이스 마이그레이션
(Django models basics reference image - Database migration )

Creating a model doesn't mean it's immediately reflected in the database. Django applies changes to the model to the database through a process called migration.

python manage.py makemigrations
python manage.py migrate

With just these two commands, your model will be made into a real database table. Pretty handy, right?

Finalize

So there you have it, the basics of Django models and understanding database structure. How did you like it? It might seem a bit complicated at first, but once you get the hang of it, you'll realize that it's a really powerful and handy tool. With Django models, you can work with complex databases with ease.

Now that you've learned the basics of Django models, why not try your hand at creating your own? You'll get a deeper understanding by actually writing and running the code. Let's go!

Glossary of terms for beginners

  • ORM: ORM stands for Object-Relational Mapping, a technology that connects objects to relational databases.
  • Migration: Django's way of reflecting changes to the model into the database schema.
  • Fields: Represent properties of the model, which correspond to columns in the database.
  • Foreign Key: A field that references the primary key of another table; used to express a one-to-many relationship.
  • Many-to-many relationships: When two models can have multiple relationships with each other.

Similar Posts