Django Primer Example of the liberated Jiang Ge--02 Manor Cloud (Database and model)

Source: Internet
Author: User

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:
    1. $mysql-U root-p

Create a database of Django projects in MySQL:
    1. 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:
    1. 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:
    1. DATABASES = {
    2. ' Default ': {
    3. ' ENGINE ': ' Django.db.backends.mysql ',
    4. ' NAME ': ' Villa ',
    5. ' USER ': ' Vamei ',
    6. ' PASSWORD ': ' Vameiisgood ',
    7. ' HOST ': ' localhost ',
    8. ' PORT ': ' 3306 ',
    9. }
    10. }
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:
    1. From django.db import Models
    2. Class Character (models. Model):
    3. Name = models. Charfield (max_length=200)
    4. def __unicode__ (self):
    5. 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:
    1. $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:
    1. $mysql-U vamei-p


To view the data model:

    1. Use Villa;
    2. SHOW TABLES;
    3. 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:

    1. INSERT into West_character (name) Values (' Vamei ');
    2. INSERT into West_character (name) Values (' Django ');
    3. INSERT into West_character (name) Values (' John ');


To view records:

    1. 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:

    1. #-*-Coding:utf-8-*-
    2. From django.http import HttpResponse
    3. From West.models import Character
    4. DEF staff (request):
    5. Staff_list = Character.objects.all ()
    6. STAFF_STR = Map (str, staff_list)
    7. 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:

    1. From Django.conf.urls import patterns, include, url
    2. Urlpatterns = Patterns ("',
    3. URL (r ' ^staff/', ' West.views.staff '),
    4. )


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)

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.