cstar

eli's docs

   :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

继 django: db howto - 1

一 操作数据库的三种方式:

[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>

 

posted on 2013-10-08 21:57  exclm  阅读(269)  评论(0编辑  收藏  举报