The liberated Jiang Ge 02 Manor-House of doubts

Source: Internet
Author: User
Tags mysql command line

Vamei Source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!

Last time, Jiang GE experience: How to set up a server, how to reply to HTTP requests, how to create an app. This time, we are going to go into the Candy Manor.

Database is a big manor, hiding a variety of treasures. A Web site without a database can provide very limited functionality.

In order to find the beloved one, Jiang Ge decided to explore this mysterious Candy Manor.

connecting to a 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.

Gangolio hesitated and walked into the gate of the manor.

Establishment 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:

Import Modelsclass Character (models. Model): name = models. Charfield (max_length=200__unicode__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 table Django_admin_log creating table Auth_permission Span style= "font-family: ' Courier New ', Courier;" >creating table auth_group_permissions creating table Auth_group creating table auth_user_groups creating table Auth_ User creating table Django_content_type 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: [email protected] Password: Pass Word (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 fromwest_character;

The last command returns the corresponding table for the character class:

+-------+--------------+------+-----+---------+---------- ------+ | Field | Type         | Null | Key | Default | Extra          | +-------+--------------+------+-----+---------+------------- ---+ | ID    | int (one)      | NO   | PRI | NULL    | auto_increment | | name  | varchar (200) | NO   |     | NULL    |                | +-------+--------------+------+-----+---------+------------- ---+ 2 rows in Set (0.00 sec) /span>

as you can see, Django also automatically adds an ID column as the primary key for the record (Primary key).

In this palatial villa, Jiang ge faint smell of sinister taste.

Show 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 ' into west_character (name)  ' 

To view records:

From West_character;

As you can see, three names have been entered into a database.

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 Httpresponsefrom west.models import Characterdef Staff (Request): Staff_list = Character.objects.all () staff_str = map (str, staff_list) return HttpResponse ( "<p> "+ "  "</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:

Import patterns, include, Urlurlpatterns = 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:

Read data from a database, displayed on the page

"My beloved one, it turns out you are here." "Jianggo self-composure, mouth can't help shaking."

Summary

Django uses classes and object interfaces to manipulate the underlying database.

With the database, there is the base of the site content.

Jiang Ge, wind and rain want to come.

Welcome to the "liberated Jiang Ge" series of articles.

The liberated Jiang Ge 02 Manor-House of doubts

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.