8、Python Django數據庫添加查詢

Python Django數據庫添加查詢html

對數據進行操做python

1、建立記錄web

# pwdshell

/root/csvt03數據庫

# ipython manage.py shelldjango

In [1]: from blog.models import Employeeide

#(第一種方法)oop

In [2]: Employeeui

Out[2]: blog.models.Employeeurl


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')


查詢數據庫已經建立了記錄


2、查詢記錄

# 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>]




3、傳遞到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>



4、啓動項目

# nohup python manage.py runserver &   (使用nohup支持後臺啓動)

相關文章
相關標籤/搜索