Coolblog Development Note Lesson 4th: Database Model Design

Source: Internet
Author: User
Tags virtual environment

Tutorials Directory

1.1 Coolblog Development Note Lesson 1th: Project Analysis

1.2 Coolblog Development Note Lesson 2nd: Building a development environment

1.3 Coolblog Development Note Lesson 3rd: Creating a Django App

Objective

My new book, "Python Crawler Development and Project Combat" , was published. This book includes basic, intermediate and in-depth three parts, not only suitable for 0 basic friends to get started, but also suitable for a certain base of crawler enthusiasts advanced, if you will not be distributed crawler, will not tens data deduplication, how to break the anti-crawler, will not analyze JS encryption , this book would surprise you. If you are interested in this book, you can look at the probation sample chapter. talk less and start talking. From the previous section we know that the home app needs to cover three sections of articles, categories and tags, in fact this is the most core function of the personal blog system: Published articles. Let's analyze how the database is designed.

1.4.1 Database Design

1. Start with the classification, from which we know that there are many categories of articles in a blog, so the classification needs to be a separate data table, which needs to store the ID and name of the classification.

2. Tags and classifications are similar, as shown below, blogs have a lot of tags tag the subject of the article, the label needs to be a separate data table, which needs to store the tag ID and name.

3. The storage of the article is relatively complex, from the project analysis of Figure 1.4 can be seen, the article data table need to store the title of the article, content, creation time, modification time, summary, classification, label , author, number of views and comments , to store the data there are several needs to note: categories, tags and number of comments .

The first time you design a data table is not to consider the number of comments, because the comments we have as a separate application, and this is related to the Comment data table and the article data table relationship, and then the comment function will be described.

In the article data table has the classification and the label field, if everybody has the design database experience, at this time should be very sensitive, when need to consider the article data table and the Classification data table, the label data table relations.

    • A category can have a lot of articles, and an article can only have a classification, which is a one-to-many relationship.
    • A label can have a lot of articles, the same article can have a lot of tags, this is a many-to-many relationship.

From the above analysis, we use MySQL Workbench to design the following three data tables:Category table,Tag table and article table, and describe the relationship between three tables.

The category table is connected to the Acticle table by a foreign key , and the tag table is unique between the article. You will find it strange why three tables have been designed, but there is an extra article_has_tag table. What is this for? In fact, this is very common in database design, the description of the two table many-to-many relationship, will generate an intermediate table, the many-to-many relationship to the two table and the intermediate table one-to-many relationship, so you can use the foreign key to connect the table. But when the code is implemented, it doesn't have to be like a acticle_has_tag intermediate table, and Django will do it for us, so let's keep looking down.

1.4.2 Writing a Database model

Open the models.py file under the Home app, which is a database model specifically designed to describe your application.

Because of the ORM approach, a class in models is a data table, and a property corresponds to a field in the data table. Let's list the category table below:

Class Category (models. Model):    #分类名称    name = models. Charfield (max_length=50,verbose_name= "category name")

In the above code, you define a database model, and you need to inherit models. The model class, name is a property in the class, and it is models. An instance of Charfield that corresponds to the Name field in the Category data table. In 1.4.1, there is also an ID field in the Category data table, and since Django will create the ID field as the primary key by default, we don't have to declare it here. Models. The initialization parameters of the Charfield class max_length represent the maximum length of the stored data, Verbose_name is used to describe the Name property and is useful when the interface is displayed. Charfield is primarily used to store short texts, which can be seen as varchar (50) in the database. Similarly, the tag class has the following contents:

Class Tag (models. Model):    # Name    = models. Charfield (max_length=50,verbose_name= "label name")

The following defines a complex acticle table, which must be read in comments. The contents are as follows:

Class article (models. Model):    # article title    = models. Charfield (max_length=70,verbose_name= "article title")    #文章内容    BODY = models. TextField (verbose_name= "article content", default= ")    #创建时间    created_time = models. Datetimefield (verbose_name= "Creation Time")    # Modified time    Modified_time = models. Datetimefield (verbose_name= "modification Time")    # summary    excerpt = models. Charfield (max_length=200, blank=true,verbose_name= "abstract")    # category Category    = models. ForeignKey (category,verbose_name= "category")    # tags tags    = models. Manytomanyfield (Tag, blank=true,verbose_name=u "label")    # author    author = models. ForeignKey (user,verbose_name= "author")    #浏览量 views    = models. Positiveintegerfield (defalut=0verbose_name= "View Amount")

  

In the above code, there are several main points to note:

  • body uses TextField to describe, it is different from Charfield, used to store a large segment of text, the default parameter is used to set the field defaults, the body default is set to NULL.
  • created_time and modified_time use Datetimefield to describe the date, and you can think about what type of storage time is used in the database.
  • excerpt is used to store the abstract of an article, and the blank=true parameter means that this field can be null.
  • category is used to represent classifications, and to describe a one-to-many relationship by passing in the category class instantiation ForeignKey.
  • Tags represent the article tags, by passing in the tag class instantiation Manytomanyfield, to express many-to-many relationships, while passing blank=true to set can be empty.
  • author said the author of the article, we will find that we use foreign keys, because the user is the Django built-in data model, Imported from Django.contrib.auth.models, specifically for handling user information, is essentially a data table. An author can have a lot of articles, and an article can have only one author, one-to-many relationships, so use the foreign key and the user data model to establish a connection.
  • views indicate the amount of browsing, through instantiation of models. Positiveintegerfield to implement, Positiveintegerfield the type only allows positive integers and 0, which means views>=0.

After the above analysis, the data model is basically built up, but this is not the end, because the model to the real database migration has not been completed. The next thing to do is to configure the database and complete the "translation" of the code into the database.

1.4.3 Database Model Migration

Open the settings.py file under the Coolblog Project Coolblog directory, where Django has already configured the Sqlite3 database by default.

  The DATABASES variable is used to configure the database, which represents the storage path for a single-file database such as Sqlite3, which uses the database engine. But this time we don't use the default Sqlite3 database, MySQL is standard in a slightly larger project. First use Navicat for MySQL to open MySQL and create a new Coolblog database.

After the new success, we then configure MySQL in the settings.py file. Modify the following:

DATABASES = {'    default ': {        ' ENGINE ': ' Django.db.backends.mysql ',        ' NAME ': ' Coolblog ', #数据库名称        ' USER ': ' Root ', #用户名        ' PASSWORD ': ', #密码为空        ' HOST ': ' 127.0.0.1 ', #主机        ' PORT ': ' 3308 ' #端口    }}

Everyone is configured according to their own MySQL. If you do not want to use MySQL, you can still remain intact. After the configuration is complete, start the database migration with the commands provided by Django. Activate the virtual environment and switch to the Coolblog project, first run the python manage.py makemigrations command will report the following error, roughly meaning that the MySQLdb module is missing.

Since we use MySQL as a database migration, we need to install the Python version of the MySQL engine, and Django uses MySQLdb by default. The next step is to install MYSQLDB, but as a person with installation experience, it is very responsible to tell everyone that MySQLdb is inconvenient to install under the Windows platform, especially when there are many Python versions, so we don't use mysqldb here. We use another more friendly and popular engine: Pymysql. We run in a virtual environment:PIP3 Install Pymysql. After the installation is successful, we need to include the following code in the __init__ file with the settings.py sibling directory:

Import Pymysqlpymysql.install_as_mysqldb ()

This replaces the Django default MySQLdb. Next, run the python manage.py makemigrations and python manage.py migrate commands. The execution effect is as follows:

This completes the migration of the database model, so let's see if the database has a new table? As shown, Django has helped us to complete the migration of the database, and there is no intermediate table that was said before!

Let us explain what the above two data model migration commands did.

    • makemigrations command: is used to record the application data model changes, these changes will be recorded in the Application Directory Migrations folder, you will see that there are some Python files generated, such as the first generation of 0001_ initial.py file.
    • The Migrate command is the real way to map the application data model to the database, and Django detects what changes we made to the data model by detecting the files under the Migrations folder, and Django translates those changes into SQL statements. And make it available for the database. For example, the Home app, the migrate command is actually checking the 0001_initial.py script generated by the makemigrations command to apply these changes to the database.

What kind of SQL statement does Django translate the changes of these models into? I can view it through the sqlmigrate command. Executed at the command line:python manage.py sqlmigrate home 0001. As shown in.

Have you found that in addition to the home application of the database model is migrated, there are many changes in data, in fact, this is a Django built-in application for data model migration. You can see with the installed_apps variable in settings.py.

This lesson is over, and the next section we'll go on to talk about the content of the request and the response.

At last

My new book, "Python Crawler Development and Project Combat" , was published. This book includes basic, intermediate and in-depth three parts, not only suitable for 0 basic friends to get started, but also suitable for a certain base of crawler enthusiasts advanced, if you will not be distributed crawler, will not tens data deduplication, how to break the anti-crawler, will not analyze JS encryption , this book would surprise you. If you are interested in this book, you can look at the probation sample chapter.

you are welcome to support me. Public number:

Coolblog Development Note Lesson 4th: Database Model Design

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.