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.
So let’s do Model first.
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
The code is pretty straightforward. ** Each Model is represented as a subclass of django.db.models.Model. ** Each model has class variables that represent a database field in the model.
** Each Field is an instance of the Field class. ** For example, the character field is represented as CharField and the date and time field is represented as DateTimeField. This tells Django what type of data to process for each field.
** Defines some Field class instances that require parameters. ** For example, CharField requires a max_length argument. This parameter is useful not only for defining database structures, but also for validating data.
** use ForeignKey to define a relationship. ** This tells Django that each (or more) ArticlePost object is associated with a User 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. ** We can also define additional things to regulate the behavior of 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 data needs to be represented. It is important to add a __str__ method to your model, which is most commonly used as an object display value in the Django admin background. Therefore, you should always return a friendly and readable string. The benefits will be seen later.
Tidy up and remove comments, and the whole code put together looks like this:
article/models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class ArticlePost(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
body = models.TextField()
created = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created'.)def __str__(self):
return self.title
Copy the code
Congratulations, you have completed most of the core data model of your blog site.
It’s less than 20 lines of code. You’ll see how powerful Django is later on.
Novices are also advised not to copy and paste code. Science shows that slow typing of characters helps improve programming.
Code into
Don’t worry if you can’t understand this part, skip it and come back to it when your level improves.
Import
The Django framework is based on python, which uses import or from… Import to import modules.
A module is actually a collection of functions and classes, which can achieve some corresponding functions. When we need to use these functions, directly import the corresponding module into our program can be used.
Import Is used to import the entire function module. In practice, however, only one function of the module is required. Therefore, importing the whole module is a bit overkill. Therefore, you can use from a import B to indicate that you can import B from module A for me.
Class (Class)
The most important concepts in Python as an object-oriented programming language are classes and instances.
Classes are abstract templates, and instances are concrete “objects” created from that class. Each object has the same method, but the data may differ. These methods are packaged together to form classes.
The ArticlePost class we just wrote, for example, provides a template for the content of blog posts. Every time a new article is created, create the author, title, body… And so on; While the details of each article may be different, they must all follow the same rules.
In Django, data is handled by a model, and the model is represented by a Class.
Field
A field represents an abstract class for a database table, which Django uses to create a database table and map Python types to the database.
In the model, fields are instantiated as class attributes and represent specific tables, and have properties and methods to map field values to the database.
For example, the ArticlePost class has a title property that holds data of type Charfield: a short string.
ForeignKey foreign key
ForeignKey
Is used to solve the “one to many” problem, used for relational query.
What is “one to many”?
In our ArticlePost model, one article can have only one author, and one author can have many articles, which is a one-to-many relationship.
Another example is that in a class, each student can only have one gender, and each gender can correspond to many students, which is also “one-to-many”.
Therefore, by associating User with ArticlePost through the ForeignKey ForeignKey, the author of the blog article and the User of the website are finally associated together.
Since there are “one to many”, there are also “one to one” and “ManyToManyField”. We don’t use these foreign keys right now, but we’ll come back to them later.
Notice the little hole here, django before 2.0on_delete
Parameters can be left blank; After Django2.0on_delete
If this parameter is mandatory, an error will be reported.
Inner Class (Meta)
The inner class Class Meta is used to work with the model metadata provided by the class. The model metadata is ** “anything that is not a field” **, such as the ordering option ordering, the database table name db_table, and the singular and plural names verbose_name and verbose_name_plural. Writing inner classes is entirely optional, and of course it helps to understand and regulate the behavior of classes.
The meta data ordering = (‘-created’,) used in class ArticlePost indicates that whenever I need to pull out a list of articles as the front page of my blog, it should be in -created order. Ensures that the latest articles are always at the top.
Data Migration (Migrations)
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.
Select My_blog, names, and hoisting from the my_blog folder in the virtual environment, and enter Python manage.py Makemigbar to create a new migration table for model changes:
(env) e:\django_project\my_blog>python manage.py makemigrations
Migrations for 'article':
article\migrations\0001_initial.py
- Create model ArticlePost
(env) e:\django_project\my_blog>
Copy the code
Django detects changes you make to model files and stores them as a migration by running Makemigbar.
Then type Python manage.py migrate to the database:
(env) e:\django_project\my_blog>python manage.py migrate
Operations to perform:
Apply all migrations: admin, article, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
...
Applying sessions.0001_initial... OK
(env) e:\django_project\my_blog>
Copy the code
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.
It’s a bit of a mouthful, and it doesn’t matter if you don’t understand it, but after the migration, you’re done writing the Model.
conclusion
This chapter takes a look at Django’s MTV schema, writes a Model ArticlePost for blog posts, and migrates it to a database.
The next step is to go to View and learn how to pull data from the model.
-
If you have any questions please leave a message on Doucet’s personal website and I will reply as soon as possible.
-
Or Email me a private message: [email protected]
-
Project code: Django_blog_tutorial
Please inform the author and indicate the source for reprinting.