First, use the simple demo to display data in the MySQL database.
From Django. Shortcuts import render_to_response
Import mysqldb
Def book_list (request ):
DB = mysqldb. Connect (user = 'me', DB = 'mydb', passwd = 'secret', host = 'localhost ')
Cursor = dB. cursor ()
Cursor.exe cute ('select name from books order by name ')
Names = [row [0] For row in cursor. fetchall ()]
DB. Close ()
Return render_to_response('book_list.html ', {'names': names })
Django supports configuring the database in settings. py in the configuration file.
For example, edit in settings. py:
Managers = admins
Databases = {
'Default ':{
'Engine': 'mysql ',
'Name': 'mydb ',
'User': 'me ',
'Password': 'secret ',
'Host': 'localhost ',
'Port ':'',
}
}
In this way, in the first code. It can be simplified:
From Django. DB import connection
Cursor = connection. cursor ()
Cursor.exe cute ('select name from Book ')
Names = [row [0] For row in cursor. fetchall ()]
Return render_to_response('book_list.html ', {'name': names })
========================================================== ========================================================
Next, we will use Django's support to create Mysql Data Modules.
1. CMD project path. Run: Python manage. py Startapp books
Books is the name of the created module. This command creates a books directory under the project.
This directory contains the created files __init _. py, models. py, tests. py, view. py
2. Open the models. py file and edit it as follows:
From Django. DB import models
Class publisher (models. Model ):
Name = models. charfield (max_length = 30)
Address = models. charfield (max_length = 50)
City = models. charfield (max_length = 60)
State_province = models. charfield (max_length = 30)
Country = models. charfield (max_length = 50)
Website = models. urlfield ()
Class author (models. Model ):
First_name = models. charfield (max_length = 30)
Last_name = models. charfield (max_length = 40)
Email = models. emailfield ()
Class book (models. Model ):
Title = models. charfield (max_length = 100)
Authors = models. manytomanyfield (author)
Publisher = models. foreignkey (publisher)
Publication_date = models. datefield ()
After the code is completed, activate the model.
3. Open the settings. py file and locate the installed_apps setting node.
Comment out the automatically generated object in it first.
Add the following code:
Installed_apps = (
# 'Django. contrib. auth ',
# 'Django. contrib. contenttypes ',
# 'Django. contrib. session ',
# 'Django. contrib. Sites ',
'Mysite. Book ',
)
Create a database table
Verify whether the model file data meets the standards in cmd. Run: Python manage. py validate
If 0 errors found is displayed, the syntax is OK.
Continue to execute Python mange. py sqlall books. This command will help you generate an SQL script. You can copy and paste the script to the database for operations.
Another method is to directly connect to the database and create a table. Command: Python manage. py syncdb
The syncdb command synchronizes your model to the database. It checks the database based on the app set in installed_apps. If the table does not exist, it is created.
Write Test method:
Def createpub (request ):
P1 = publisher (name = 'apache', address = '1970 Telegraph Avenue ', city = 'berkeley', state_province = 'CA', Country = 'U. s. a', website = 'HTTP: // www.sina.com.cn ')
P1.save ()
P2 = publisher (name = 'B world', address = '1970 Telegraph Avenue', city = 'beijinging', state_province = 'cn', Country = 'hk ', website = 'HTTP: // www.qq.com ')
P2.save ()
Pub = publisher. Objects. Filter (name = 'apress ')
Return render_to_response('book_list.html ', {'name': pub })
Write the corresponding template page and URL configuration.
The running effect is as follows:
[<Publisher: Publisher Object>, <Publisher: Publisher Object>]
The printed content does not get the desired result. solve this problem first.
Modify the content of the models. py file as follows:
Class publisher (models. Model ):
Name = models. charfield (max_length = 30)
Address = models. charfield (max_length = 50)
City = models. charfield (max_length = 60)
State_province = models. charfield (max_length = 50)
Country = models. charfield (max_length = 50)
Website = models. urlfield ()
Def _ Unicode _ (Self ):
Return self. Name
Class author (models. Model ):
First_name = models. charfield (max_length = 30)
Last_name = models. charfield (max_length = 40)
Email = models. emailfield ()
Def _ Unicode _ (Self ):
Return u '% S % s' % (self. first_name, self. last_name)
Class book (models. Model ):
Title = models. charfield (max_length = 100)
Authors = models. manytomanyfield (author)
Publisher = models. foreignkey (publisher)
Publication_date = models. datefield ()
Def _ Unicode _ (Self ):
Return self. Title
Run again and the output is normal. There are still many operations in objects. Please refer to the corresponding document for more information.