Reference: Django builds a Personal Blog: The Model for writing blog posts
The Django framework focuses on models, templates, and Views, known as the MTV pattern.
Their respective responsibilities are as follows:
level | Duties and responsibilities |
---|---|
The Model, or data access layer | Handles all transactions related to data: how it is accessed, validated, what actions are involved, and how the data relates to each other. |
Templates are the business logic layer | Handle presentation-related decisions: how to display on a page or other type of document. |
View, the presentation layer | Logic for accessing the model and fetching the appropriate templates. Bridge between model and template. |
Simply put, the Model retrieves and retrieves data, the View decides what data needs to be retrieved, and the Template takes care of presenting the retrieved data in a reasonable manner.
The first step in writing a database-driven Web application in Django is to define the Model, which is the database structure design and additional metadata.
The model contains the fields and behaviors necessary for the stored data. The goal with Django is that you only need to define the data model, and you don’t have to worry about the rest of the code, which is automatically generated from the model.
Write the Model
As mentioned earlier, Django typically maps a Model to a database and handles data-related transactions.
For a blog site, the most important data is the article. So first to build a data model for storing articles.
Open the article/models.py file and enter the following code:
article/models.py
from django.db import models
Import the built-in User model.
from django.contrib.auth.models import User
# timezone is used to handle time-dependent transactions.
from django.utils import timezone
# Blog post data model
class ArticlePost(models.Model) :
# article writer. The on_delete parameter is used to specify the deletion method to avoid data inconsistency between two associated tables.
author = models.ForeignKey(User, on_delete=models.CASCADE)
# Article title. Models. CharField is a string field used to hold short strings, such as titles
title = models.CharField(max_length=100)
# Body of the article. Save a lot of text using TextField
body = models.TextField()
# article creation time. The default=timezone.now parameter specifies the current time at which it will default to write data when it is created
created = models.DateTimeField(default=timezone.now)
# Post update time. The auto_now=True parameter specifies that the current time is automatically written each time data is updated
updated = models.DateTimeField(auto_now=True)
Copy the code
- Each model is represented by
django.db.models.Model
A subclass of class.- Each model has class variables that represent a database field in the model.
- Every field is
Field
Class. For example, character fields are represented byCharField
, the date and time fields are represented asDateTimeField
. This tells Django what type of data to process for each field.- Define some
Field
Class instances require parameters. For example,CharField
The need for aMax_length parameters
. This parameter is useful not only for defining database structures, but also for validating data.- use
ForeignKey
Define a relationship. This will tell Django that each (or more)ArticlePost
Objects are all associated with oneUser
Object. Django itself has a simple and complete account system (User) that can handle basic functions such as account application, creation, permissions, and groups.
The ArticlePost class defines the elements necessary for an article: author, title, body, creation date, and update date. There are additional things we can define to regulate the behavior of the data in ArticlePost. Add the following code:
article/models.py
...
class ArticlePost(models.Model) :.The inner class class Meta is used to define metadata for the model
class Meta:
Ordering specifies the orderin which the model returns data
# '-created' indicates that data should be sorted in reverse order
ordering = ('-created'.)The function __str__ defines the content of the return value when the STR () method of an object is called
def __str__(self) :
# return self.title Returns the title of the article
return self.title
Copy the code
The ordering in the inner Meta class defines how data is ordered. -created indicates that the created articles are sorted in reverse order, ensuring that the latest articles are always at the top of the page. Note that the ordering is a tuple. If the parentheses contain only one element, do not forget the comma at the end. The __str__ method defines the name that should be displayed when the data needs to be represented. It is important to add a __str__ method to your model, which is most commonly used as a display value for objects in the Django admin background. Therefore, you should always return a friendly and readable string.
Data migration
With the Model written, the next step is data migration.
Migration is how Changes Django makes to the model are transferred to the database. Therefore, whenever changes (add, modify, delete, and so on) are made to the database, data migration is required.
Djangos migration code is automatically generated by your model files. It is essentially just a history that Django can use to scroll through database updates to match the current model.
Type Python manage.py Makemigrations to create a new migration table for changes to the model.
Django detects changes you make to model files and stores them as a migration by running Makemigbar.
Then type Python manage.py migrate to migrate the application to the database.
The migrate command selects all migrations that have not yet been performed and applies them to the database, that is, synchronizing changes to the model to the database structure. Migration is a powerful feature that allows you to continually change the database structure during development without having to re-delete or create tables. It focuses on making database upgrades smooth without losing data.