• django: db howto


    继 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>
  • 相关阅读:
    poj 3087 直接模拟
    POJ-3126 BFS,埃式筛选及黑科技
    POJ3278-Catch That Cow
    js变量提升
    饿了么
    2分钟就能学会的【Google/百度搜索大法】了解一下?
    span标签间距
    Vue移动端项目如何使用手机预览调试
    Port 3000 is already in use
    koa2第一天 async详解
  • 原文地址:https://www.cnblogs.com/exclm/p/3358040.html
Copyright © 2020-2023  润新知