django 数据库操作及页面显示

插入数据方法

方法一:

ipython manage.py shell

from blog.models import Employee

emp = Employee()  创建实例对象

emp.name = 'Alen'

emp.save() 

从数据库查看数据是否入库

select *from blog_employee

方法二:直接在构造方法中把值传入

emp = Employee(name="tom")

emp.save()

方法三:类对象管理方式

Employee.objects.cre

Employee.objects.creat(name = "max")

emp.save()

或者

emp = Employee.objects.create(name ="km")

emp.save()

-----------------------------------------------

查看数据

emps = Employee.objects.all()

emps

emps[0].id

emps[0].name

方法二:

在models.py 中添加一个方法

当我们的对象以字符串展现的时候,name显示出来

from django.db import models

class Employee(models.Model):

name = models.CharField(max_length=100)

def __unicode__(self):

return self.name

重新打开ipython manage.py shell

from blog.models import Employee

emps = Employee.objects.all()

emps

显示每个字段的名称

------------------------------------------------------

在页面上显示数据库数据

1.在url.py 中添加

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

# Uncomment the next two lines to enable the admin:

# from django.contrib import admin

# admin.autodiscover()

urlpatterns = patterns('',

    # Examples:

    # url(r'^$', 'csvt03.views.home', name='home'),

    # url(r'^csvt03/', include('csvt03.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:

    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:

    # url(r'^admin/', include(admin.site.urls)),

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

)

2.在views.py中添加

# Create your views here.

from django.shortcuts import render_to_response

from blog.models import Employee

def index(req):

emps = Employee.objects.all()

return render_to_response('index.html',{'emps':emps})

#return render_to_response('index.html',{'dic':dic,'user':user})

3.在项目blog中添加文件夹

mkdir templates

在templates文件夹中添加一个index.html文件

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 

"http://www.w3.org/TR/html4/loose.dtd">

<html>

 <head>

  <title> New Document </title>

  <meta name="Generator" content="EditPlus">

  <meta name="Author" content="">

  <meta name="Keywords" content="">

  <meta name="Description" content="">

 </head>

 <body>

  {{emps}}

  {% for emp in emps%}

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

  {% endfor%}

  <div>共有{{empslength}}记录</div>

</html>

4.运行python manage.py runserver  就能查看到数据库返回内容

相关推荐