Django Model Creation
In this guide, you will learn how to create data models for your blog application using Django ORM (Object-Relational Mapping). On your Ubuntu 22.04 virtual server instance, we will define the Post and Comment models, introduce them to the project, and convert these models into database tables.
1. Starting Django and Defining Models
In Django projects, components are kept within separate applications to maintain modularity. In this guide, we will create a separate Django application for the blog.
1.1 Creating Applications
First, activate your Python virtual environment and navigate to the project directory:
cd ~/my_blog_app/blog
. env/bin/activate
Then run the following command to create a new Django application:
python manage.py startapp genixnode_blog
This command creates a new Django application named genixnode_blog.
1.2 Writing Post and Comment Models
We will define the Post and Comment models by editing the models.py file in the application directory. The Post model will represent blog posts, and the Comment model will represent the comments made on these posts.
nano genixnode_blog/models.py
Add the following code to this file:
from django.db import models
from django.template.defaultfilters import slugify
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(unique=True, max_length=255)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
author = models.TextField() # Gerekirse User modeline dönüştürülebilir
def get_absolute_url(self):
return reverse('blog_post_detail', args=[self.slug])
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
class Meta:
ordering = ['created_on']
def __str__(self):
return self.title
class Comment(models.Model):
name = models.CharField(max_length=42)
email = models.EmailField(max_length=75)
website = models.URLField(max_length=200, null=True, blank=True)
content = models.TextField()
post = models.ForeignKey(Post, on_delete=models.CASCADE) # Bire-Çok ilişkisi kurar
created_on = models.DateTimeField(auto_now_add=True)
Remarks:
We added fields such as post title, content, author and creation date to the post model.
In the Comment model, we created a ForeignKey relationship that specifies the owner of the comment, its content and which article it belongs to.
2. Introducing the Application to the Project and Migration Procedures
In order for the newly created models to find a counterpart in the database, they must be introduced to the project.
2.1 Updating the settings.py File
To introduce our new application to the project, let's add the genixnode_blog application to the INSTALLED_APPS list in the settings.py file:
INSTALLED_APPS = [
'genixnode_blog', # Yeni uygulamayı projeye dahil ediyoruz
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
2.2 Creating and Applying Migration Files
We need to run migration commands to apply model changes to the database.
Generating LoA Files
cd ~/my_blog_app/blog
python manage.py makemigrations
Applying Migrations
python manage.py migrate
This command creates the necessary tables for the Post and Comment models in the MySQL database.
3. Verifying the Database Schema
After the migration is complete, let's check the tables in the database.
3.1 Connecting to MySQL
mysql blog_data -u genix_user
After selecting the database:
USE blog_data;
SHOW TABLES;
3.2 Examining the Table Structure
We can check the structure of the Comment table we just created as follows:
DESCRIBE genixnode_blog_comment;
In the same way we can check the structure of the Post table:
DESCRIBE genixnode_blog_post;
Frequently Asked Questions (FAQ)
- What is the advantage of using Django ORM?
ORM (Object-Relational Mapping) allows managing database operations using Python classes and methods instead of writing SQL queries. This reduces code duplication and increases portability.
- What is the difference between makemigrations and migrate?
makemigrations detects changes to model classes and prepares Python/SQL files (migration files) to implement these changes. migrate takes these prepared migration files and applies them to the real database, that is, creates/updates the tables.
- What does ForeignKey do?
ForeignKey establishes a One-to-Many relationship between two models. For example, it indicates that many comments belong to a single post. The on_delete=models.CASCADE setting ensures that when the main record (Post) is deleted, all associated child records (Comments) are also automatically deleted.
- What is the main difference between CharField and TextField in Django?
CharField is used for short, usually single-line text (max_length is required), while TextField is used for multi-line text (such as blog post content), which can be of unlimited length.
Result
In this guide, you learned how to set up a One-to-Many relationship, create models, and manage database schemas in Django. You can manage your database efficiently by using Django's migration and model structures. You can easily implement these methods on GenixNode virtual server instances.

