一 操作数据库的三种方式:
[root@bogon csvt03]# python2.7 manage.py shell Python 2.7.5 (default, Sep 20 2013, 07:02:05) >>> from blog.models import Employee >>> emp = Employee() >>> emp.name="One" >>> emp.save() >>> emp = Employee(name="Two") >>> emp.save() >>> emp = Employee.objects.create(name='Three') >>> emp.save() >>>
查看效果:
[root@bogon csvt03]# mysql -uroot -p Enter password:
mysql> use csvt; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> select * from blog_employee; +----+-------+ | id | name | +----+-------+ | 1 | One | | 2 | Two | | 3 | Three | +----+-------+ 3 rows in set (0.00 sec) mysql>
manage.py shell 调试技巧:
>>> all=Employee.objects.all() >>> all [<Employee: Employee object>, <Employee: Employee object>, <Employee: Employee object>] >>> all[1].id 2L >>> all[0].name u'One' >>>
可以在 Employee 对象中添加实例方法 __unicode__(self) 以方便调试:
>>> from blog.models import Employee >>> all=Employee.objects.all() >>> all [<Employee: One>, <Employee: Two>, <Employee: Three>] >>>
二 使用数据库中的内容:
修改 urls.py,添加 index 路径:
url(r'^index/$','blog.views.index'),
views.py:
from django.shortcuts import render_to_response as r2r from blog.models import Employee def index(req): emps = Employee.objects.all() return r2r('index.html', {'emps':emps})
index.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Django DB</title> </head> <body> {% for emp in emps %} <div>{{forloop.counter}} : {{emp}}</div> {% endfor %} </body> </html>