Use python and Django to migrate the blog database, pythondjango

Source: Internet
Author: User
Tags virtual environment

Use python and Django to migrate the blog database, pythondjango

The configuration of the basic blog and the generation of the project have been completed in the previous section. This time, I started to learn about some basic operations of my blog mainly on the database.

1. design the blog database table structure

The main function of a blog is to display the articles we write. It needs to obtain the blog article data from somewhere to display the articles. Generally, this is the database. We keep the written articles permanently in the database. When a user accesses our blog, Django will go to the database to extract the data and present it to the user.

Blog posts should contain titles, texts, authors, posting times, and other data. A more modern blog post also hopes to include classification, tags, and comments. To better store the data, we need to properly organize the table structure of the database.

Our initial blog version mainly includes blog articles, which are classified and tagged. An article can only have one category, but many tags can be added.

Article id title body posting time classification tag
1 title 1 text 1 2016-12-23 Django Learning
2 title 2 text 2 2016-12-24 Django Learning
3 title 3 text 3 2016-12-26 Python Learning

The Document ID is a number that uniquely corresponds to an article. Of course, there can be more columns to store more relevant data. This is just a basic example.

The database table can be designed like this, but after a slight analysis, we will find that the classification and tags of the three articles are the same, which will generate a lot of duplicate data, storage space is wasted when the data volume is large.

Different articles may correspond to the same category or tag. Therefore, we extract the categories and tags into a separate database table, and then associate the articles with categories and tags. The following table lists the database tables for classification and tags:

CATEGORY id category name

1 Django
2 Python

Tag id tag name

1 Django Learning
2 Python Learning

Next we will compile our database model:

The above is a natural language description table. The database, like the programming language, has its own set of prescribed syntaxes to generate the above table structure so that we can store the data. Generally, at this time, we should first learn the syntax for creating tables in the database, and then come back to write our Django Blog Code. However, Django tells us that we don't need to be so troublesome. It has already helped us with some things. Django converts the syntax of that database to the syntax of Python. You only need to write Python code. Django translates the Python code into the corresponding database operating language. In a more professional way, Django provides us with an ORM (Object Relational Mapping) system.

For example, in our database table of classification, Django only requires us to write like this:

blog/models.pyfrom django.db import modelsclass Category(models.Model): name = models.CharField(max_length=100)

Complete code is provided:

From django. db import modelsfrom django. contrib. auth. models import Userfrom django. utils. six import python_2_unicode_compatible # python_2_unicode_compatible decorators are used to be compatible with Python2 @ python_2_unicode_compatibleclass Category (models. model): "Django requires that the Model must inherit models. model class. Category only requires a simple classification name. CharField specifies the Data Type of the category name. CharField is character type. The max_length parameter of CharField specifies its maximum length. A category name that exceeds this length cannot be saved to the database. Of course, Django also provides a variety of other data types, such as DateTimeField and integer IntegerField. Django built-in all types of viewing documentation: https://docs.djangoproject.com/en/1.10/ref/models/fields/#field-types "name = models. charField (max_length = 100) def _ str _ (self): return self. name @ python_2_unicode_compatibleclass Tag (models. model): "Tag is also relatively simple, just like Category. Again, we must inherit the models. Model class! "Name = models. charField (max_length = 100) def _ str _ (self): return self. name @ python_2_unicode_compatibleclass Post (models. model): the database table in the "" Article is a little more complex, mainly involving more fields. "# Article title = models. CharField (max_length = 70) # Article body, we use TextField. # CharField can be used to store short strings, but the text of the article may be a large text segment. Therefore, TextField is used to store large text segments. Body = models. TextField () # these two columns indicate the document creation time and the last modification time respectively. The field storing time is of the DateTimeField type. Created_time = models. DateTimeField () modified_time = models. DateTimeField () # Article abstract. No article abstract can be found. However, by default, CharField requires us to store data; otherwise, an error is reported. # The null value can be allowed after the value of blank = True of CharField is specified. Excerpt = models. CharField (max_length = 200, blank = True) # This is classification and tag. We have defined the classification and tag model above. # Here we associate the database table corresponding to the document with the database table corresponding to the category and tag, but the association form is slightly different. # We stipulate that an article can only correspond to one category, but there can be multiple articles under one category, so we use ForeignKey, that is, one-to-many associations. # For tags, an article may have multiple tags, and there may be multiple articles under the same tag. Therefore, we use ManyToManyField to indicate that this is a many-to-many relationship. # At the same time, we stipulate that there can be no tags in the article, so we specify blank = True for tags. # If you do not know ForeignKey, ManyToManyField, please refer to the explanation in the tutorial, also refer to the official documentation: # https://docs.djangoproject.com/en/1.10/topics/db/models/#relationships category = models. foreignKey (Category) tags = models. manyToManyField (Tag, blank = True) # author of the article. Here, the User is from django. contrib. auth. models import. # Django. contrib. auth is a built-in Django application used to process Website User registration, logon, and other processes. User is a User model that Django has prepared for us. # Here we associate the article with the User through ForeignKey. # Because we stipulate that one article can only have one author, and one author may write multiple articles, this is a one-to-many Association, similar to Category. Author = models. ForeignKey (User) def _ str _ (self): return self. title

Category is a standard Python class that inherits the models. Model class and the class name is Category. The Category class has a property name, which is an instance of models. CharField.

In this way, Django can translate this class into the database's operating language and create a table named category in the database. A column name of this table is name. There is also a column id, Django will automatically create. It can be seen that when the Python code is translated into a database language, its rule is that a Python class corresponds to a database table. The class name is the table name, and the class attribute corresponds to the table column, the attribute name is the column name.

We need three tables: Post, Category, and Tag. Next we will write their corresponding Python classes. The model code is usually written in the models. py file of the relevant application.

Ii. database migration

In order for Django to complete the translation and create these database tables, we once again asked my project management assistant manage. py. Activate the virtual environment, switch to the directory where the manage. py file is located, and run the python manage. py makemigrations and python manage. py migrate commands respectively:

Note: If the Code contains Chinese comments and you are using the Python 2 development environment, you will get an Encoding Error. Therefore, add the encoding declaration # coding: UTF-8 at the beginning of a file containing Chinese comments.

When we runpython manage.py makemigrationsAfter that, Django generated a 000w.initial.py file in the migrations \ directory of the blog application. This file is a file that Django uses to record the modifications made to the model. Currently, three model classes are created in the models. py file. Django records these changes in 000w.initial.py.

However, it only tells Django what changes we have made. In order for Django to create a database table for us, it then executespython manage.py migrateCommand. Django detects the files in the migrations \ directory of the application, learns what operations we have performed on the database, and then translates these operations into database operation languages, these operations are then applied to the real database.

You can see that besides Applying blog.0001 _ initial... OK, Django also operates on other files. This is because in addition to our own blog applications, Django also has many built-in applications, which also need to store data. In settings. pyINSTALLED_APPSee these applications in settings, of course we do not need to care about these.

blogproject/settings.pyINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog',]

For those who know the database language, you can run the following command to see What Django has done for us:

python manage.py sqlmigrate blog 0001

You will see that the statements for creating database tables translated by Django are output, which helps you understand the working mechanism of Django ORM.

Iii. Select database version

Without installing any database software, Django helped us migrate the database. This is because we use the Python built-in SQLite3 database.

SQLite3 is a lightweight database with only one file. You can see that there is an additional db. sqlite3 file under the project root directory. This is the SQLite3 database file, and the data of the Django blog will be stored in this database file.

Django made some default database configuration for us in settings. py:

Blogproject/settings. py ## other configuration options... DATABASES = {'default': {'Engine ': 'django. db. backends. sqlite3 ', 'name': OS. path. join (BASE_DIR, 'db. sqlite3 '), }}## other configuration options...

The default database engine is SQLite3.

Of course, some people tend to use MySQL and other large databases. As for how Django configures MySQL, we will not go into details here. You can use the search engine or refer to Django's official documentation to solve this problem. For a small blog, the SQLite3 database is sufficient.

4. operate databases using Django

The primary operation of a database is to store data in it, retrieve data from it, modify saved data, and delete unnecessary data. Like creating a database table, Django provides a complete set of methods for these operations to free us from the database language. We don't have to learn how to use the database language to complete these operations. Simply calling several Python functions can satisfy our needs.

Store Data

First, we will explore these functions in the command line and learn how to use Django to operate the database. Run the python manage. py shell command in the directory where manage. py is located:

Create a category and a tag:

First, import the three previously written model classes, and then instantiateCategoryClass andTagClass for their attributesnameAssigned value. In order for Django to save the data to the databasesaveMethod.

Try creating another article, but before creating an article, we need to create a User to specify the author of the article. The User Creation command Django has been written for us and is still running through manage. py. First, press Ctrl + c to exit the command interaction bar (several times in a row if one exit fails) and runpython manage.py createsuperuserCommand and follow the prompts to create a user:

(The password is too simple to pass)

Run againpython manage.py shellGo to the Python command interaction bar and create an article:

Since we restarted the shell, we need to re-import it.Category,Tag,PostAndUser. We also imported timezone, a helper module provided by Django, because we need to call itnow()Method:created_timeAndmodified_timeTime specified, easy to understandnowMethod returns the current time. Then, based on the user name and classification namegetMethod to retrieveUserAndCategory(The method for getting data is described below ). Then we specifytitle,body,created_time,modified_timeAnd associate it with the previously created Category and User. Allowed to be emptyexcerpt,tagsWe didn't specify values for them.

Note: We usegetMethodCategoryOfnameThe value of the attribute to obtain a record of the category.Category.objects.get(name='category test')The meaning is to retrieve from the databasenameThe value is the classification record of category test. Make sure that there is only one record with the value of category test in the database. OtherwisegetMethod returnsMultipleObjectsReturnedException. If you have accidentally stored multiple records, delete them. For details about how to delete data, see the following section.

Retrieve Data

The data has been stored in the database. Now let's take a look at them:

objectsIs our model manager, which provides us with a series of methods to retrieve data from the database. Here we useallMethod. We can see thatallAll methods return data, which should be stored before, but the displayed string is a bit strange and cannot be seen whether it is the data we saved previously. To make the displayed data more user-friendly, we add one for the three models.__str__Method:

From django. db import modelsfrom django. contrib. auth. models import Userfrom django. utils. six import python_2_unicode_compatible # python_2_unicode_compatible decorators are used to be compatible with Python2 @ python_2_unicode_compatibleclass Category (models. model): "Django requires that the Model must inherit models. model class. Category only requires a simple classification name. CharField specifies the Data Type of the category name. CharField is character type. The max_length parameter of CharField specifies its maximum length. A category name that exceeds this length cannot be saved to the database. Of course, Django also provides a variety of other data types, such as DateTimeField and integer IntegerField. Django built-in all types of viewing documentation: https://docs.djangoproject.com/en/1.10/ref/models/fields/#field-types "name = models. charField (max_length = 100) def _ str _ (self): return self. name @ python_2_unicode_compatibleclass Tag (models. model): "Tag is also relatively simple, just like Category. Again, we must inherit the models. Model class! "Name = models. charField (max_length = 100) def _ str _ (self): return self. name @ python_2_unicode_compatibleclass Post (models. model): the database table in the "" Article is a little more complex, mainly involving more fields. "# Article title = models. CharField (max_length = 70) # Article body, we use TextField. # CharField can be used to store short strings, but the text of the article may be a large text segment. Therefore, TextField is used to store large text segments. Body = models. TextField () # these two columns indicate the document creation time and the last modification time respectively. The field storing time is of the DateTimeField type. Created_time = models. DateTimeField () modified_time = models. DateTimeField () # Article abstract. No article abstract can be found. However, by default, CharField requires us to store data; otherwise, an error is reported. # The null value can be allowed after the value of blank = True of CharField is specified. Excerpt = models. CharField (max_length = 200, blank = True) # This is classification and tag. We have defined the classification and tag model above. # Here we associate the database table corresponding to the document with the database table corresponding to the category and tag, but the association form is slightly different. # We stipulate that an article can only correspond to one category, but there can be multiple articles under one category, so we use ForeignKey, that is, one-to-many associations. # For tags, an article may have multiple tags, and there may be multiple articles under the same tag. Therefore, we use ManyToManyField to indicate that this is a many-to-many relationship. # At the same time, we stipulate that there can be no tags in the article, so we specify blank = True for tags. # If you do not know ForeignKey, ManyToManyField, please refer to the explanation in the tutorial, also refer to the official documentation: # https://docs.djangoproject.com/en/1.10/topics/db/models/#relationships category = models. foreignKey (Category) tags = models. manyToManyField (Tag, blank = True) # author of the article. Here, the User is from django. contrib. auth. models import. # Django. contrib. auth is a built-in Django application used to process Website User registration, logon, and other processes. User is a User model that Django has prepared for us. # Here we associate the article with the User through ForeignKey. # Because we stipulate that one article can only have one author, and one author may write multiple articles, this is a one-to-many Association, similar to Category. Author = models. ForeignKey (User) def _ str _ (self): return self. title

Defined__str__The interpreter displays__str__Method. HereCategoryReturn category namename,TagReturns the tag name, whilePostReturns itstitle.

python_2_unicode_compatibleThe decorator is compatible with Python 2. If you use the Python3 development environment, removing this decorator will not have any impact. If you are using the Python2 development environment and do not want to use this decorator__str__Change the method__unicode__Method.

Press Ctrl + c to exit the Shell and then run it again.python manage.py shellGo to Shell.

Change Data:

First passgetMethod By category namenameObtain the value "category test" to the category and modify itsnameProperty is the new value category test new, and then callsaveMethod To save the modification to the database. Then we can see that the data returned by the database is already the modified value.Tag,Post.

Delete data:

First, according to the titletitleThe value is retrieved from the database.Post, Saved in the VariablepAnd then call itsdeleteMethod.Post.objects.all()An empty QuerySet (similar to a list) is returned, indicating that there is no Post in the database and the Post has been deleted.

This is how Django adds, deletes, modifies, and queries databases. In addition to the Methods demonstrated above, Django also provides a lot of other methods for us. Some of these methods will be used in the tutorial, and I will explain their usage at that time. But when you develop your own projects in the future, you need to read the Django official documentation to learn what methods are available and how to use them.

In the above Article, the migration of blog databases using python and Django is all the content that I have shared with you. I hope you can give us a reference and support for more customers.

Related Article

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.