In the previous chapter, Jiang GE's first experience: How to set up a server, how to reply to an HTTP request, and how to create an app. This time, we are going to go into the Candy Manor.
In order to find the beloved one, Jiang Ge decided to explore this mysterious Candy Manor.
1. Connect to the database
Django provides a unified calling API for multiple database backgrounds. Depending on the requirements, Django can choose a different database background. MySQL is the most commonly used database. We'll connect Django with MySQL here.
Start MySQL under the Linux terminal:
- $mysql-U root-p
Create a database of Django projects in MySQL:
- mysql> CREATE DATABASE Villa DEFAULT Charset=utf8;
Here, UTF8 is used as the default character set to support Chinese. Create a user for the Django project in MySQL and grant the relevant permissions:
- Mysql> GRANT SELECT, INSERT, UPDATE, DELETE, create, DROP, INDEX, ALTER, create temporary TABLES, LOCK TABLES on Villa. * to ' vamei ' @ ' localhost ' identified by ' Vameiisgood ';
In settings.py, change the Databases object to:
- DATABASES = {
- ' Default ': {
- ' ENGINE ': ' Django.db.backends.mysql ',
- ' NAME ': ' Villa ',
- ' USER ': ' Vamei ',
- ' PASSWORD ': ' Vameiisgood ',
- ' HOST ': ' localhost ',
- ' PORT ': ' 3306 ',
- }
- }
The background type is MySQL. It contains the database name and the user's information, which is the same as the corresponding database and user settings in MySQL. Django is connected to the corresponding database and user in MySQL based on this setting. After that, Django can read and write in the database.
2. Create a model
MySQL is a relational database. But with Django's help, we don't have to write SQL statements directly. Django Converts a relational table (tables) into a class. Each record is an object under the Class (object). We can use the object-based approach to manipulate the relational MySQL database.
In traditional MySQL, the data model is a table. Under Django, a table is a class. Each column of the table is a property of the class. In models.py, we create a table with only one column, that is, a class with only one property:
- From django.db import Models
- Class Character (models. Model):
- Name = models. Charfield (max_length=200)
- def __unicode__ (self):
- Return Self.name
Class character defines the data model, which needs to inherit from models. Model. In MySQL, this class is actually a table. Table has only one column, which is name. As you can see, the Name property is a character type with a maximum length of 200. The class character has a __unicode__ () method that describes how the object is expressed in characters. If it is Python 3, define the __STR__ () method to implement the same functionality.
Command the Django synchronization database. Django actually creates the individual relational tables in MySQL based on the data model described in models.py:
- $python manage.py syncdb
After synchronizing the database, Django will build the relevant MySQL table and ask you to create a super User: Creating tables ...
Creating Table Django_admin_log
Creating Table Auth_permission
Creating Table Auth_group_permissions
Creating Table Auth_group
Creating Table Auth_user_groups
Creating Table Auth_user_user_permissions
Creating Table Auth_User
Creating Table Django_content_type
Creating Table Django_session
Creating Table West_character
You just installed Django's auth system, which means you don ' t has any superusers defined.
Would to create one now? (yes/no): Yes
Username (leave blank to use ' Tommy '): Vamei
Email Address:
Password:
Password (again):
Superuser created successfully.
Installing Custom SQL ...
Installing indexes ...
Installed 0 object (s) from 0 fixture (s)
The data model was established. Open the MySQL command line:
- $mysql-U vamei-p
To view the data model:
- Use Villa;
- SHOW TABLES;
- SHOW COLUMNS from West_character;
The last command returns the corresponding table for the character class:
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| ID | Int (11) | NO | PRI | NULL | auto_increment |
| name | varchar (200) | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
2 rows in Set (0.00 sec)
As you can see, Django also automatically adds an ID column as the primary key for the record (Primary key).
3. Display data
Although the data model has been established, there is no data input. For simplicity, we add records manually. Open the MySQL command line and switch to the appropriate database. To add a record:
- INSERT into West_character (name) Values (' Vamei ');
- INSERT into West_character (name) Values (' Django ');
- INSERT into West_character (name) Values (' John ');
To view records:
- SELECT * from West_character;
Below we take the data out of the database and return it to the HTTP request. In west/views.py, add a view. For the corresponding request, we will read all the records from the database and then return to the client:
- #-*-Coding:utf-8-*-
- From django.http import HttpResponse
- From West.models import Character
- DEF staff (request):
- Staff_list = Character.objects.all ()
- STAFF_STR = Map (str, staff_list)
- Return HttpResponse ("<p>" + ". Join (STAFF_STR) +" </p> ")
As you can see, we introduced the character class from the West.models. By manipulating the class, we can read the records in the table
In order for the HTTP request to find the above program, add the URL navigation in west/urls.py:
- From Django.conf.urls import patterns, include, url
- Urlpatterns = Patterns ("',
- URL (r ' ^staff/', ' West.views.staff '),
- )
Run the server. Enter the URL in the browser:
127.0.0.1:8000/west/staff
To see the effect:
4. Summary
Django uses classes and object interfaces to manipulate the underlying database.
With the database, there is the base of the site content.
Django Primer Example of the liberated Jiang Ge--02 Manor Cloud (Database and model)