Build a Django Blog application and Database model

Source: Internet
Author: User
Tags auth virtual environment

1. Create our Django Blog app now, and I'll name it blog. Activate the virtual Environment , enter the directory where the manage.py file is located, run the python manage.py startapp blog command to create a blog application

The folder structure of this app Django has been built for us, but it's just a folder that contains a variety of files, and Django doesn't yet know it's an app. We have to tell Django that this is the app we built, and the professional point is to register the app in the Django configuration file. Open the Blogproject\ directory under the settings.py file, see the name will know settings.py is a settings file (setting meaning to set), find the INSTALLED_APPS settings, add the blog app.

2. Database model

The main function of the blog is to show the article we write, it needs to get the blog post data from somewhere to show the article, usually this place is the database. We keep the written articles permanently in the database, and when users visit our blogs, Django goes to the database and takes the data out to the user.

The data stored in the database is actually the form of a table, such as the database table that stores the blog post:

Article ID title Body Publication Time category label
1 Title 1 Text 1 2016-12-23 Django Django Learning
2 Title 2 Text 2 2016-12-24 Django Django Learning
3 Title 3 Text 3 2016-12-26 Python Python Learning

Where the article ID is a number, the only one that corresponds to an article. Of course there are more columns to store more relevant data, which is just one of the most basic examples.

database table Design So it is actually possible, but a little analysis we will find a problem, the 3 articles are the same classification and tags, which will produce a lot of duplication, when the amount of data is very large waste of storage space. Different articles may have their corresponding categories or tags are the same, so we take the classification and tags out, make a separate database table, and then the article and classification, Tag Association. The following are the database tables for classification and labeling, respectively:

Category ID Category name
1 Django
2 Python
Tag ID Label name
1 Django Learning
2

Python Learning

Blog/Models.Py# Coding:utf-8FromDjango.dbImportModelsFromDjango.contrib.auth.modelsImportUserClassCategory(Models.Model):"""Django requires the model to inherit models. Model class.Category requires only a simple category name name.Charfield Specifies the data type of the class name name, Charfield is the character type,The max_length parameter of the Charfield specifies its maximum length, and the classification name beyond that length cannot be stored in the database.Of course, Django also provides us with a number of other data types, such as datetime type Datetimefield, integer type Integerfield, and so on.All Django built-in types can view documents:https://docs.djangoproject.com/en/1.10/ref/models/fields/#field-types"""Name=Models.Charfield(Max_length=100)ClassTag(Models.Model):"""Tag tags are also relatively simple, the same as Category.Again, we must inherit models. Model Class!"""Name=Models.Charfield(Max_length=100)ClassPost(Models.Model):"""The database table of the article is slightly more complex, mainly involving more fields."""# article titleTitle=Models.Charfield(Max_length=70)# article text, we used the TextField.# Storing shorter strings can use Charfield, but may be a large piece of text for the body of the article, so use TextField to store large pieces of text.Body=Models.TextField()# These two columns represent the creation time and last modification time of the article, with the Datetimefield type for the stored Time field.Created_time=Models.Datetimefield()Modified_time=Models.Datetimefield()# article Summary, may not have the article summary, but by default the Charfield request we must deposit the data, otherwise will have the error.# you can allow null values after specifying the Blank=true parameter value for Charfield.Excerpt=Models.Charfield(Max_length=200,Blank=True)# This is the category with labels, categories and labels that we have defined on top of the model.# Here we associate the database tables of the article with the database tables that correspond to the categories and tags, but the association forms are slightly different.# We require an article to correspond to only one category, but a category can have multiple articles, so we are using ForeignKey, a one-to-many relationship.# and for labels, an article can have multiple labels, and there may be multiple articles under the same label, so we use Manytomanyfield to show that this is a many-to-many relationship.# at the same time we stipulate that the article can have no tags, so the tag tags are specified blank=true.# If you don't know ForeignKey and Manytomanyfield, please see the explanations in the tutorial, and also refer to the official documentation:# https://docs.djangoproject.com/en/1.10/topics/db/models/#relationshipsCategory=Models.foreignkey (category) tags = models. Manytomanyfield (tagblank=< Span class= "BP" >true) # article author, where User is imported from Django.contrib.auth.models. # Django.contrib.auth is a Django built-in app designed to handle the process of registering and logging on to website users, which is a user model that Django has written for us. # Here we associate the article with the User through ForeignKey. # because we stipulate that an article can have only one author, and an author may write multiple articles, so this is a one-to-many association, similar to Category. author = models. Foreignkey (user) 


Understand the relationship between many-to-one and many-to-many associations

We used two types of relational database tables: ForeignKey and Manytomanyfield.

ForeignKey

ForeignKeyIndicates a one-to-many association relationship. For example, here our article and classification of the relationship, an article can only correspond to one category, and a category can have more than one article. Reactions to database tables, where they are actually stored:

article ID title Body category ID
1 Title 1 Body 1 1
2 Title 2 Body 2 1
3 Title 3 Body 3 1
4 Title 4 Body 4 2
category ID Category name  
1 Django
2 Python

You can see that articles and classifications are actually associated with the column ID in the article database table. When you want to query which category the article belongs to, you only need to see how much its corresponding category ID is, and then, based on that category ID, you can find the data for that category from the Classification database table. For example, this article 1, 2, 3 corresponds to the classification ID of 1, and the classification ID of 1 is named Django, so the article 1, 2, 3 belongs to categorical Django. Similarly article 4 belongs to the taxonomy Python.

Conversely, to find out which articles are under a category, just look for the articles that should be categorized as IDs. For example, Django has a classification ID of 1, and the corresponding Category ID 1 article an article 1, 2, 3, so there are 3 articles under category Django.

Hopefully this example will help you deepen your understanding of many-to-one relationships and how they are correlated in the database, and more examples are given at the end of this article for Django's official reference.

Manytomanyfield

ManyToManyFieldIndicates a many-to-many correlation, such as articles and tags here, an article can have more than one label, and a label can have more than one article. Reactions to database tables, where they are actually stored:

article ID title Body
1 Title 1 Body 1
2 Title 2 Body 2
3 Title 3 Body 3
4 Title 4 Body 4
tag ID Label name
1 Django Learning
2 Python Learning
article ID tag ID
1 1
1 2
2 1
3 2

Many-to-many relationships can no longer be associated with an example of a one-to-many relationship in the article database table plus a list of category IDs , so an additional table is required to record the association between the article and the label. For example, the article ID 1 of the article, which corresponds to the label ID 1 of the label, also corresponds to the label ID 2 of the label, that is, article 1 belongs to the label 1:django Learning, but also belongs to the label 2:python learning 。

Conversely, the label ID 1 of the label, both corresponding to the article ID 1 of the article, also corresponds to the article ID 2 article, that is, the label 1:django Learning has two articles.

< Span class= "C1" > < span class= "n" > < Span class= "o" > Hopefully this example will help you deepen your understanding of the many-to-many relationships and how they are associated in the database, and more examples of Django's official references at the end of the text         

Create a Django Blog app and database model

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.