码迷,mamicode.com
首页 > 数据库 > 详细

八、Python Django数据库添加查询

时间:2016-09-08 18:41:54      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:python django数据库添加查询

Python Django数据库添加查询

对数据进行操作

一、创建记录

# pwd

/root/csvt03

# ipython manage.py shell

In [1]: from blog.models import Employee

#(第一种方法)

In [2]: Employee

Out[2]: blog.models.Employee


In [3]: emp = Employee()


In [4]: emp.name = ‘Alen‘


In [5]: emp.save()


#(第二种方法)

In [6]: emp = Employee(name=‘Tom‘)


In [7]: emp.save()


#(第三种方法)

调用管理器create

In [8]: Employee.objects.create(name=‘Max‘)


查询数据库已经创建了记录


二、查询记录

# ipython manage.py shell

In [13]: emps = Employee.objects.all()


In [14]: emps

Out[14]: [<Employee: Employee object>, <Employee: Employee object>, <Employee: Employee object>, <Employee: Employee object>]


In [16]: emps[0].id

Out[16]: 1L


In [17]: emps[0].name

Out[17]: u‘Alen‘


In [18]: emps[1].name

Out[18]: u‘Tom‘


In [19]: emps[2].name

Out[19]: u‘Max‘


# cat blog/models.py


from django.db import models


class Employee(models.Model):

    name = models.CharField(max_length=20)

    def __unicode__(self):    # 通过__unicode__使查询出来的数据以字符串的方式显示

        return self.name


# ipython manage.py shell

In [1]: from blog.models import Employee


In [2]: emp = Employee.objects.all()


In [3]: emp

Out[3]: [<Employee: Alen>, <Employee: Tom>, <Employee: Max>, <Employee: Sumer>]




三、传递到web页面显示查询结果

# 添加URL,以及添加index.html模板文件

# egrep -v "#|^$" urls.py


from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns(‘‘,

      url(r‘^index/$‘,‘blog.views.index‘),

)


# egrep -v "#|^$" blog/models.py


from django.db import models

class Employee(models.Model):

    name = models.CharField(max_length=20)

    def __unicode__(self):

        return self.name


# egrep -v "#|^$" blog/templates/index.html


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

    <title>Loyu Django test</title>

</head>

<body>

{% for emp in emps %}

<div>{{forloop.counter}}:{{emp}}</div>

{% endfor %}

<div>共有记录</div>

</body>

</html>



四、启动项目

# nohup python manage.py runserver &   (使用nohup支持后台启动)


本文出自 “流星宇” 博客,请务必保留此出处http://8789878.blog.51cto.com/8779878/1850751

八、Python Django数据库添加查询

标签:python django数据库添加查询

原文地址:http://8789878.blog.51cto.com/8779878/1850751

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!